Skip to content

Fix #15000: Propagate integral cast ranges with path-safe value flow - #8819

Open
jfdeverge wants to merge 1 commit into
cppcheck-opensource:mainfrom
jfdeverge:dev/fix_misra_14_3
Open

jfdeverge wants to merge 1 commit into
cppcheck-opensource:mainfrom
jfdeverge:dev/fix_misra_14_3

Conversation

@jfdeverge

@jfdeverge jfdeverge commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

There was missing detection of 'MISRA C:2012 Rule 14.3" on some specific code structure generated by Matlab Simulink coder.
We identified these issues by comparing its results with reports previously generated by our company’s internal tool on the same software.

The bug report would have looked like below.

Problem

Cppcheck did not report a MISRA C:2012 Rule 14.3 violation when a comparison
used an integer expression whose range was provably bounded by casts and
constant arithmetic. The existing check handled a variable compared with a
value outside the variable's declared type range, but did not evaluate this
equivalent expression form.

Minimal Reproducer

typedef unsigned int uint32;
typedef unsigned long long uint64;
typedef long long sint64;

void f(uint32 x)
{
    uint64 tmp = ((uint64)x) + 1ULL;
    if (tmp > 4294967295ULL)
        tmp = 4294967295ULL;

    if ((((sint64)((uint32)tmp)) - 1LL) > 4294967295LL) {
    }
}

After the clamp and casts, the left-hand expression cannot exceed
UINT32_MAX - 1. Therefore the final condition is always false and produces
the knownConditionTrueFalse diagnostic. The company's end-to-end MISRA
postprocessor mapping was not exercised here.

Observed Behavior

Before the fix, the final comparison produced no diagnostic. This allowed the
generated-code pattern to pass through the cppcheck-based MISRA pipeline
without the expected Rule 14.3 finding.

Comment thread lib/checkcondition.cpp Fixed
Comment thread test/testcondition.cpp Resolved
@chrchr-github

Copy link
Copy Markdown
Collaborator

I have created this ticket: https://trac.cppcheck.net/ticket/15000

@jfdeverge

Copy link
Copy Markdown
Contributor Author

I will update the commit message with Fix #15000 ...

Comment thread lib/checkcondition.cpp Resolved
Comment thread lib/checkcondition.cpp Resolved
@danmar

danmar commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator

The PR title should be updated. The commit message will not be shown in the git log but the PR title will.

@jfdeverge jfdeverge changed the title Fix Rule 14.3 detection for bounded expressions Fix #15000 CheckCondition: detect compareValueOutOfTypeRange for bounded cast/arithmetic expressions Sep 6, 2026
@jfdeverge

Copy link
Copy Markdown
Contributor Author

The PR title should be updated. The commit message will not be shown in the git log but the PR title will.

Done.

PR title updated to "Fix #15000 CheckCondition: detect compareValueOutOfTypeRange for bounded cast/arithmetic expressions" ; let me know if better convention would apply here.

Comment thread lib/checkcondition.cpp Resolved
Comment thread lib/checkcondition.cpp Resolved
Comment thread lib/checkcondition.cpp Resolved
Comment thread test/testcondition.cpp Resolved
@danmar danmar changed the title Fix #15000 CheckCondition: detect compareValueOutOfTypeRange for bounded cast/arithmetic expressions Fix #15000 (CheckCondition: detect compareValueOutOfTypeRange for bounded cast/arithmetic expressions) Sep 6, 2026
@danmar

danmar commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator

The PR title should be updated. The commit message will not be shown in the git log but the PR title will.

Done.

PR title updated to "Fix #15000 CheckCondition: detect compareValueOutOfTypeRange for bounded cast/arithmetic expressions" ; let me know if better convention would apply here.

Thanks! I don't have a strict pattern that must be followed but I typically put parentheses around the ticket title. Most important is that you indicated which ticket it solves..

Comment thread lib/checkcondition.cpp Resolved
Comment thread lib/checkcondition.cpp Resolved
Comment thread lib/checkcondition.cpp Resolved
Comment thread lib/checkcondition.cpp Resolved
@chrchr-github

Copy link
Copy Markdown
Collaborator

I have a feeling that some of the logic should be performed in ValueFlow and not in the check. Currently, ValueFlow only seems to handle bool value ranges. @danmar What do you think?

@danmar

danmar commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

I have a feeling that some of the logic should be performed in ValueFlow and not in the check. Currently, ValueFlow only seems to handle bool value ranges. @danmar What do you think?

I agree that checkers should have some nice way to determine min/max values for an expression.

If that is put in ValueFlow or a utility function I don't have a strong opinion it depends on what is more efficient.

@chrchr-github

Copy link
Copy Markdown
Collaborator

I have a feeling that some of the logic should be performed in ValueFlow and not in the check. Currently, ValueFlow only seems to handle bool value ranges. @danmar What do you think?

I agree that checkers should have some nice way to determine min/max values for an expression.

If that is put in ValueFlow or a utility function I don't have a strong opinion it depends on what is more efficient.

I meant that ValueFlow should determine that the condition is always true/false, instead of having complex parsing logic (in this case, for casts and arithmetic) in the checker.

@jfdeverge jfdeverge changed the title Fix #15000 (CheckCondition: detect compareValueOutOfTypeRange for bounded cast/arithmetic expressions) Fix #15000 Propagate integral cast ranges to condition analysis Sep 12, 2026
Comment thread lib/vf_common.cpp Resolved
Comment thread test/testcondition.cpp Resolved
@jfdeverge
jfdeverge force-pushed the dev/fix_misra_14_3 branch 2 times, most recently from 1f38959 to 1ebcbe5 Compare September 14, 2026 07:13
@jfdeverge

Copy link
Copy Markdown
Contributor Author

I rebased against main (no conflicts).

Comment thread lib/valueflow.cpp Resolved

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

I found no new problems in this version. In my tests, every result that differs from base is a correct new warning or a wrong base warning that is now gone.

New results in this version that are correct:

  • The PR's reproducer pattern (with stdint.h names and a >= 4294967294LL variant) is now reported as always false.
  • (uint16_t)(uint8_t)x > 255 is now reported as always false.
  • On avr8, the PR removes base's wrong results for us + 1 == 0, us == -1 and signed char c == 0xFFFFu.
  • A uint8_t decremented in place no longer gets a false "always false" warning.
  • _Bool b = 5; b == 1 is now reported as always true. Base reported it as always false, which was wrong.

Problems that comments.md already lists are not repeated here.

Testing

Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestType, TestStl, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.

Python CLI tests: in test/cli/other_test.py, the tests matching -k "15000 or missing_include or unique_error" give 5 passed. The new floating_strict… and unsigned_loop_index… tests give 3 passed.

Base vs PR comparison: I ran both builds with --enable=style,warning --platform=unix64 and compared the output. For e.c I also used --platform=avr8. The test files are in /work/scratch:

  • a.c: conversions on assignment. Float to int, out-of-range values for unsigned char, signed char, short, unsigned and _Bool, a uint8_t wrapping on ++, and a 64-bit value cast to int. Results are the same as base, except that _Bool b = 5; b == 1 is now correctly reported as always true (base said always false).
  • b.c: casts with arithmetic and comparisons. There is one correct new warning: (uint16_t)(uint8_t)x > 255 is always false. Base's false "always false" for uint8_t c = (uint8_t)x; c += 10; if (c < 10) is gone.
  • c.c, h.c: for loops. These cover &&/|| conditions, start values that are negative or come from a condition or a cast, and values after the loop. They give the same warnings as base. Some negativeIndex messages now name the condition that the value comes from.
  • d.c: shift counts. Shift counts from ternaries and conditions give the same results as base.
  • e.c: compareValueOutOfTypeRange with promotions and mixed signs. On unix64 the results are the same as base. On avr8 (16-bit int) the PR removes base's wrong warnings for us + 1 == 0, us == -1 and signed char c == 0xFFFFu, and correctly adds unsignedLessThanZero for us*2 < 0.
  • f.c: values from function arguments and casts through local variables. Same results as base.
  • g.c: the PR's reproducer pattern and variations. The new always-false results for ((int64_t)((uint32_t)x)) - 1LL > 4294967295LL and >= 4294967294LL are correct. There are no new false positives. (int32_t)x - 65535 > 0 with a uint16_t x is still not reported, the same as base. This is a limitation, not a regression.

Real code: I also ran both builds on test/cfg/{std.c,std.cpp,posix.c,gnu.c,windows.cpp} (with --library), lib/mathlib.cpp, lib/token.cpp and tinyxml2.cpp. The output was the same for base and the PR, and the run times were about the same: std.c took 5 s with base and 4 s with the PR, std.cpp took 7 s and 6 s.


Automated review of 56f0fa9 by Claude. The pull request was built and tested locally.

@dmcppcheck

Copy link
Copy Markdown
Contributor

Test results for commit 56f0fa9 (tools/test-my-pr.py, main compared to this PR):

Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-8819/
packages: 1000
Differing warnings: 3829 (+1723 -2106)
AI review: 4 acceptable regression, 28 improvement, 18 neutral (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-8819/2026-11-05_05-50-22-56f0fa953836-review.txt)
Timing: +0.1% (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-8819/2026-11-05_05-50-22-56f0fa953836_timing.html)

Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong.

@danmar

danmar commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator

can you please comment on the "Still open" :

Still open:

  1. containerOutOfBounds false positive on the resize guard (first review, inline comment on test/teststl.cpp:529). if (v.size() < entries + 2) v.resize(entries + 2); v[0] = 1; still warns. The PR still changes the test's expected
    result from "" to the warning instead of fixing the cause.
  2. Index arithmetic on an unsigned loop counter is no longer checked (review of 7a618a4). for (unsigned i = 0; i < 10; i++) a[i + 1] = 0; gives nothing; base reports index 10. All five variants fail (size_t i, a[2*i], buf[i+1] with
    sizeof, int i with a[i + 1u]), also with --check-level=exhaustive. This is the most serious open item.
  3. Plain signed char compared to 0xFF is no longer reported (review of 76f6fb3). char c; if (c == 0xFF), c == 200, *s == 0xEF, c > 127 and c == 128 give nothing on unix64 and win64; base reports all of them. The existing #11592
    regression test (test/testcondition.cpp:6895) is still changed to expect "".
  4. Plain char handling still differs between the checker and ValueFlow. This is the root cause of item 3: the checker ignores platform.defaultSign, while the PR's ValueFlow code uses it.

Fixed (verified by running the reproducers):

  • negativeIndex with i-- > -3 in the loop condition, and with an init value that may be negative
  • s + 1u == 0u and i + 1 == 0 are kept
  • float uninitvar false positive and floatConversionOverflow false positive
  • Negative value cast to unsigned/size_t is still found (the reported index is now 2147483648 or LLONG_MAX instead of 4294967295, which is only a message change)
  • char c == 300 and similar
  • --platform=unspecified early return is back
  • && loop off-by-one
  • Bitfield bits leaking into the dump for ~, << and ++
  • ~ on cast bounds
  • y -= 1 / y-- after a cast
  • Narrow signed i++ wrapping
  • Values lost through a (char) cast
  • wchar_t on Windows
  • Flag enum 0x80000000
  • || loop zerodiv false positive
  • (uint32_t)x - 1u == 0xFFFFFFFFu (the AI comment you posted)
  • Comments from the claude[bot] review: the getValueLE change is reverted, the copying is now conditional, and a test for unknown sign was added

@danmar

danmar commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

I do have a good feeling about this PR. And if you feel some AI reviews are out-of-scope for this PR then feel free to suggest that we create tickets in Trac for some AI reviews... it's important that we don't introduce false positives but false negatives are acceptable if there is a Trac ticket..

@dmcppcheck

Copy link
Copy Markdown
Contributor

This pull request has merge conflicts that must be resolved.

@jfdeverge
jfdeverge force-pushed the dev/fix_misra_14_3 branch 4 times, most recently from bd99e76 to 28017f4 Compare November 10, 2026 13:00
@jfdeverge

Copy link
Copy Markdown
Contributor Author

I can do a couple of iterations to improve, most of these AI reviews were meaningful.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

New false negative: a narrowing (or same-size) integral cast or assignment of a value whose range is already bounded by conditions now loses that range. Base reports these conditions, and the PR does not. For example, if (x < 0 || x > 100) return; if ((uint8_t)x > 200) is no longer reported as always false. The same happens with (int8_t)x < 0, (short)x > 200, static_cast<uint8_t>(x), and with assignments like uint8_t c = x; and short s = (short)x;.

The cause is that the cast handles each value on its own. x has the excluded ranges !<=-1 and !>=101, and each one on its own does not survive narrowing. Only the pair proves that the range fits. So the cast token keeps only the type bounds, {!<=-129,!>=128} or {!<=-1,!>=256}, and the <=100 bound is lost. This is a common clamp-then-narrow pattern, so it should be fixed or tracked in a Trac ticket, as danmar suggested for false negatives.

I found no new false positives or crashes. The items that were still open in C108 are fixed in this version:

  • the containerOutOfBounds resize guard;
  • a[i + 1] with an unsigned loop index;
  • plain char compared with 0xFF or 127, and the #11592 test is restored.

Earlier comments

57 earlier comments, 0 open
# Comment By Where Status
1 Warning text/ID wrong: 4294967295 is in range for signed long long @chrchr-github test/testcondition.cpp:6559 ✅ Fixed
2 Use getSizeOf instead of the switch over types @aadanen lib/checkcondition.cpp:1984 ✅ Fixed
3 Unknown sign should return false, not be treated as unsigned @aadanen lib/checkcondition.cpp:2020 ✅ Fixed
4 PR title should be updated @danmar general ✅ Fixed
5 C++ casts have two operands @danmar lib/checkcondition.cpp:2034 ❔ Code removed
6 Unclear which code is targeted @danmar lib/checkcondition.cpp:2050 ❔ Code removed
7 Always returns false for unary +/- @danmar lib/checkcondition.cpp:2059 ❔ Code removed
8 Use existing utility for integer type min/max @danmar lib/checkcondition.cpp:1975 ✅ Fixed
9 Check for similar existing utility function @danmar lib/checkcondition.cpp:2019 ✅ Fixed
10 Pass platform instead of settings @danmar lib/checkcondition.cpp:2020 ❔ Code removed
11 Consider impossible values when no known value @danmar lib/checkcondition.cpp:2026 ✅ Fixed
12 Logic should be in ValueFlow, not the checker @chrchr-github general ✅ Fixed
13 Unsigned 64-bit max equals signed max @aadanen lib/vf_common.cpp:99 💬 Answered: bigint cannot represent ULLONG_MAX; conservative max kept
14 Use uint32_t instead of typedefs in tests @chrchr-github test/testcondition.cpp:6549 ✅ Fixed
15 containerOutOfBounds FP on resize guard AI review general ✅ Fixed
16 negativeIndex bypass ignores loop condition (i-- > -3) AI review general ✅ Fixed
17 No-wrap check loses s+1u==0u and i+1==0 results AI review general ✅ Fixed
18 teststl expectation changed to accept containerOutOfBounds FP AI review test/teststl.cpp:529 ✅ Fixed
19 Induction-variable bypass does not check the loop condition AI review lib/checkbufferoverrun.cpp:401 ✅ Fixed
20 Range bounds dropped when no-wrap proof fails AI review lib/vf_settokenvalue.cpp:511 ✅ Fixed
21 uninitvar FP for float/long double after >=/<= comparison AI review general ✅ Fixed
22 Value::unknown() used as float false-branch value gives uninitvar AI review lib/valueflow.cpp:5120 ✅ Fixed
23 floatConversionOverflow FP from float bounds AI review general ✅ Fixed
24 Bounded float values read as concrete by checkFloatToIntegerOverflow AI review lib/valueflow.cpp:5110 ✅ Fixed
25 Negative value cast to unsigned/size_t loses arrayIndexOutOfBoundsCond AI review general ✅ Fixed
26 negativeIndex lost when init may be negative AI review general ✅ Fixed
27 Plain char compared with 300 no longer reported AI review general ✅ Fixed
28 Check runs with --platform=unspecified AI review general ✅ Fixed
29 Bounded value dropped on cast instead of converted AI review lib/vf_settokenvalue.cpp:188 ✅ Fixed
30 Assignment version of negative-to-unsigned FN AI review lib/valueflow.cpp:4102 ✅ Fixed
31 any_of accepts init with some negative values AI review lib/checkbufferoverrun.cpp:392 ✅ Fixed
32 Plain char skipped in compareValueOutOfTypeRange AI review lib/checkcondition.cpp:2328 ✅ Fixed
33 Unspecified platform early return removed AI review lib/checkcondition.cpp:2072 ✅ Fixed
34 arrayIndexOutOfBounds lost for a[i+1] with unsigned loop index AI review general ✅ Fixed
35 Loop range dropped at unsigned +/* in setTokenValue AI review lib/vf_settokenvalue.cpp:620 ✅ Fixed
36 FN after for loop with && condition AI review general ✅ Fixed
37 Bitfield width leaks into result type of ~ in dump AI review general ✅ Fixed
38 valueFlowForLoopSimplifyAfter skipped for partial conditions AI review lib/valueflow.cpp:5661 ✅ Fixed
39 getCommonIntegralType copies whole ValueType (bits) AI review lib/symboldatabase.cpp:7552 ✅ Fixed
40 Plain signed char compared with 0xFF no longer reported AI review general ✅ Fixed
41 Checker ignores platform.defaultSign for plain char AI review lib/checkcondition.cpp:2129 ✅ Fixed
42 #11592 regression test expectation changed to empty AI review test/testcondition.cpp:6846 ✅ Fixed
43 Bitfield width leaks on ++/-- path AI review general ✅ Fixed
44 ~ on cast bound does not flip bound kind (FP) AI review general ✅ Fixed
45 ~ keeps bound direction AI review lib/valueflow.cpp:1056 ✅ Fixed
46 y -= 1 / y-- after cast reported as never wrapping AI review general ✅ Fixed
47 evalAssignment shifts bound without no-wrap check AI review lib/valueflow.cpp:1058 ✅ Fixed
48 Narrow signed i++ after cast treated as non-wrapping AI review general ✅ Fixed
49 Guard only stops unsigned types in vf_analyzers AI review lib/vf_analyzers.cpp:286 ✅ Fixed
50 Cast to plain char drops all values AI review general ✅ Fixed
51 castValue returns false for UNKNOWN_SIGN char AI review lib/vf_settokenvalue.cpp:226 ✅ Fixed
52 wchar_t treated as signed 16-bit on Windows (FP) AI review general ✅ Fixed
53 wchar_t range from getSizeOf with SIGNED fallback AI review lib/checkcondition.cpp:2134 ✅ Fixed
54 Enum compared with 0x80000000 enumerator reported always false AI review general ✅ Fixed
55 Known value trusted to fit enum's signed int type AI review lib/checkcondition.cpp:2128 ✅ Fixed
56 || loop gives possible lastValue+1 past init (zerodiv FP) AI review general ✅ Fixed
57 After-loop value ignores initValue > lastValue AI review lib/valueflow.cpp:5668 ✅ Fixed

Testing

Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestType, TestStl, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.

CLI tests: pytest other_test.py -k "15000 or floating or unsigned_loop or bounded or missing_include" gives 7 passed.

New false negative: bounded value through a narrowing cast or assignment (t3.c)

#include <stdint.h>
void use(int);
void d3(int x) { if (x < 0 || x > 100) return; if ((int8_t)x < 0) use(3); }
void e1(int x) { if (x < 0 || x > 100) return; if ((uint8_t)x > 200) use(1); }
void e2(int x) { if (x < 0 || x > 100) return; if ((short)x > 200) use(2); }
void e3(int x) { if (x < 0 || x > 100) return; if ((long long)x > 200) use(3); }
void e4(int x) { if (x < 0 || x > 100) return; uint8_t c = x; if (c > 200) use(4); }

Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}' t3.c

Base:

3:knownConditionTrueFalse:Condition '(int8_t)x<0' is always false
4:knownConditionTrueFalse:Condition '(uint8_t)x>200' is always false
5:knownConditionTrueFalse:Condition '(short)x>200' is always false
6:knownConditionTrueFalse:Condition '(long long)x>200' is always false
7:knownConditionTrueFalse:Condition 'c>200' is always false

PR: only the line 6 warning, the widening cast.

--debug for line 3 shows:

  • x {!<=-1,>=0,!>=101,<=100}
  • ( always {!<=-129,!>=128}

The C++ versions behave the same: static_cast<uint8_t>(x) > 200, short s = (short)x; s > 200, and unsigned char a[4]; a[0] = x; a[0] == 200. Base reports all three and the PR reports none of them, also with --check-level=exhaustive.

Earlier findings checked again: these reproducers now give correct results (no false positive, or the expected warning):

  • containerOutOfBounds resize guard;
  • unsigned loop index a[i+1];
  • char c == 0xFF and c > 127;
  • wchar_t on win64;
  • flag enum 0x80000000;
  • || loop zerodiv;
  • float uninitvar;
  • floatConversionOverflow;
  • && loop off-by-one;
  • negativeIndex with if (x >= 0) {};
  • negative value cast to unsigned;
  • y -= 1 after a cast.

Other comparisons: about 40 cast and arithmetic cases (t1.c, t2.c) gave no new false positives. The PR removes several wrong base results, for example:

  • (unsigned)x > 10u with x in [-5, 5];
  • unsigned char c = (unsigned char)x; c++; c == 0;
  • y + 65536u == 0 with y = (uint16_t)x * 65536u.

Automated review of 28017f4 by Claude. The pull request was built and tested locally.

Comment thread lib/vf_settokenvalue.cpp Resolved
@jfdeverge
jfdeverge force-pushed the dev/fix_misra_14_3 branch 6 times, most recently from 655683a to fc51719 Compare November 11, 2026 10:50

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

New false negative: the clamp-then-narrow fix only works when the cast is inside the branch of a separate if. When the range check and the narrowing cast are in the same && chain, the same ?: condition, or the same while condition, the cast keeps only its type bounds. Base reports these as always false and the PR does not:

  • if (x >= 0 && x <= 100 && (uint8_t)x > 200)
  • the same with (int8_t)x < 0 and (short)x > 200
  • if (x < 0 || x > 100 || (uint8_t)x > 200)
  • (x >= 0 && x <= 100) ? (uint8_t)x > 200 : 0
  • while (x >= 0 && x <= 100 && (uint8_t)x > 200)

The cause is isConditionFactActiveAtUse(): it needs conditionBranchAtUse() to put the use in a true or false branch of an if/while. A use in the right-hand operand of &&/||/?: is not in such a branch, so the facts from the condition are rejected. This is only a false negative.

The C113 case (if (x < 0 || x > 100) return; then a narrowing cast or assignment) is fixed in this version. I found no new false positives, crashes or slowdowns.

Earlier comments

63 earlier comments, 0 open
# Comment By Where Status
1 Warning text/ID wrong: 4294967295 fits signed long long @chrchr-github test/testcondition.cpp:6559 ✅ Fixed
2 Use getSizeOf instead of the switch over types @aadanen lib/checkcondition.cpp:1984 ✅ Fixed
3 Unknown sign should return false, not be treated as unsigned @aadanen lib/checkcondition.cpp:2020 ✅ Fixed
4 PR title should be updated @danmar general ✅ Fixed
5 C++ casts have two operands @danmar lib/checkcondition.cpp:2034 ❔ Code removed
6 Unclear which code is targeted @danmar lib/checkcondition.cpp:2050 ❔ Code removed
7 Always returns false for unary +/- @danmar lib/checkcondition.cpp:2059 ❔ Code removed
8 'signed long long' in the message is confusing @danmar test/testcondition.cpp:6559 ✅ Fixed
9 Use existing utility for integer type min/max @danmar lib/checkcondition.cpp:1975 ✅ Fixed
10 Check for a similar existing utility function @danmar lib/checkcondition.cpp:2019 ✅ Fixed
11 Pass platform instead of settings @danmar lib/checkcondition.cpp:2020 ❔ Code removed
12 Consider impossible values when there is no known value @danmar lib/checkcondition.cpp:2026 ✅ Fixed
13 Logic should be in ValueFlow, not in the checker @chrchr-github general ✅ Fixed
14 Unsigned 64-bit max equals signed max @aadanen lib/vf_common.cpp:99 💬 Answered: bigint cannot represent ULLONG_MAX; conservative max kept
15 Use uint32_t instead of typedefs in tests @chrchr-github test/testcondition.cpp:6549 ✅ Fixed
16 Unsigned wrap-around FP for (uint32_t)x - 1u == 0xFFFFFFFFu @danmar lib/valueflow.cpp:1039 ✅ Fixed
17 containerOutOfBounds FP on resize guard AI review general ✅ Fixed
18 negativeIndex bypass ignores the loop condition AI review general ✅ Fixed
19 No-wrap check loses s+1u==0u and i+1==0 results AI review general ✅ Fixed
20 teststl expectation changed to accept containerOutOfBounds FP AI review test/teststl.cpp:529 ✅ Fixed
21 Induction-variable bypass does not check the loop condition AI review lib/checkbufferoverrun.cpp:401 ✅ Fixed
22 Range bounds dropped when the no-wrap proof fails AI review lib/vf_settokenvalue.cpp:511 ✅ Fixed
23 uninitvar FP for float/long double after >=/<= comparison AI review general ✅ Fixed
24 Value::unknown() used as the float false-branch value AI review lib/valueflow.cpp:5120 ✅ Fixed
25 floatConversionOverflow FP from float bounds AI review general ✅ Fixed
26 Bounded float values read as concrete by checkFloatToIntegerOverflow AI review lib/valueflow.cpp:5125 ✅ Fixed
27 Negative value cast to unsigned/size_t loses arrayIndexOutOfBoundsCond AI review general ✅ Fixed
28 negativeIndex lost when the init value may be negative AI review general ✅ Fixed
29 Plain char compared with 300 no longer reported AI review general ✅ Fixed
30 Check runs with --platform=unspecified AI review general ✅ Fixed
31 Bounded value dropped on a cast instead of converted AI review lib/vf_settokenvalue.cpp:188 ✅ Fixed
32 Assignment version of the negative-to-unsigned FN AI review lib/valueflow.cpp:4117 ✅ Fixed
33 any_of accepts an init value that may be negative AI review lib/checkbufferoverrun.cpp:392 ✅ Fixed
34 Plain char skipped in compareValueOutOfTypeRange AI review lib/checkcondition.cpp:2328 ✅ Fixed
35 Unspecified platform early return removed AI review lib/checkcondition.cpp:2072 ✅ Fixed
36 arrayIndexOutOfBounds lost for a[i+1] with an unsigned loop index AI review general ✅ Fixed
37 Loop range dropped at unsigned +/* in setTokenValue AI review lib/vf_settokenvalue.cpp:641 ✅ Fixed
38 FN after a for loop with an && condition AI review general ✅ Fixed
39 Bitfield width leaks into the result type of ~ in the dump AI review general ✅ Fixed
40 valueFlowForLoopSimplifyAfter skipped for partial conditions AI review lib/valueflow.cpp:5679 ✅ Fixed
41 getCommonIntegralType copies the whole ValueType (bits) AI review lib/symboldatabase.cpp:7552 ✅ Fixed
42 Plain signed char compared with 0xFF no longer reported AI review general ✅ Fixed
43 Checker ignores platform.defaultSign for plain char AI review lib/checkcondition.cpp:2129 ✅ Fixed
44 #11592 regression test expectation changed to empty AI review test/testcondition.cpp:6846 ✅ Fixed
45 Bitfield width leaks on the ++/-- path AI review general ✅ Fixed
46 ++/-- copies the operand's whole ValueType AI review lib/symboldatabase.cpp:7531 ✅ Fixed
47 ~ on cast bounds does not flip the bound kind (FP) AI review general ✅ Fixed
48 ~ handler keeps the bound direction AI review lib/valueflow.cpp:1051 ✅ Fixed
49 y -= 1 / y-- after a cast reported as never wrapping AI review general ✅ Fixed
50 evalAssignment shifts the bound without a no-wrap check AI review lib/valueflow.cpp:1053 ✅ Fixed
51 Narrow signed i++ after a cast treated as non-wrapping AI review general ✅ Fixed
52 Guard only stops unsigned types in vf_analyzers AI review lib/vf_analyzers.cpp:286 ✅ Fixed
53 Cast to plain char drops all values AI review general ✅ Fixed
54 castValue returns false for UNKNOWN_SIGN char AI review lib/vf_settokenvalue.cpp:226 ✅ Fixed
55 wchar_t treated as signed 16-bit on Windows (FP) AI review general ✅ Fixed
56 wchar_t range from getSizeOf with the SIGNED fallback AI review lib/checkcondition.cpp:2134 ✅ Fixed
57 Enum compared with a 0x80000000 enumerator reported as always false AI review general ✅ Fixed
58 Known value trusted to fit the enum's signed int type AI review lib/checkcondition.cpp:2128 ✅ Fixed
59 || loop gives a possible lastValue+1 past the init value (zerodiv FP) AI review general ✅ Fixed
60 After-loop value ignores initValue > lastValue AI review lib/valueflow.cpp:5686 ✅ Fixed
61 Comment on the still-open items (resize guard, unsigned loop index, plain char) @danmar general ✅ Fixed
62 Bounded value loses its range through a narrowing cast or assignment AI review general ✅ Fixed
63 Bounds converted one by one, so clamp-then-narrow is lost AI review lib/vf_settokenvalue.cpp:248 ✅ Fixed

Testing

Build: make -j4 cppcheck testrunner in pr/ and make -j4 cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestType, TestStl, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.

CLI tests: pytest other_test.py -k "15000 or floating or unsigned_loop or bounded or missing_include or cast" gives 8 passed.

Regression: narrowing cast in the same condition as the range check (n3.c)

#include <stdint.h>
void use(int);
void a8(int x) { if (x >= 0 && x <= 100 && (uint8_t)x > 200) use(9); }
void c1(int x) { if (x >= 0 && x <= 100 && (int8_t)x < 0) use(1); }
void c2(int x) { if (x >= 0 && x <= 100 && (short)x > 200) use(2); }
void c3(int x) { if (x >= 0 && x <= 100 && (long long)x > 200) use(3); }
void c4(int x) { if (x < 0 || x > 100 || (uint8_t)x > 200) use(4); }
void c5(int x) { if (x >= 0 && x <= 100) if ((uint8_t)x > 200) use(5); }
int c6(int x) { return x >= 0 && x <= 100 && (uint8_t)x > 200; }

Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}' n3.c

Base reports lines 3 to 9 as always false. PR output:

6:knownConditionTrueFalse:Condition '(long long)x>200' is always false
8:knownConditionTrueFalse:Condition '(uint8_t)x>200' is always false

--debug for line 3 with the PR:

( always {!<=-1,!>=256}
x {>=0,!<=-1,<=100,!>=101}

The excluded bounds of x are there, but the cast does not combine them.

The ternary and loop forms behave the same way (n4.c):

int t1(int x) { return (x >= 0 && x <= 100) ? (uint8_t)x > 200 : 0; }
void w1(int x) { while (x >= 0 && x <= 100 && (uint8_t)x > 200) x++; }

Base reports (uint8_t)x>200 as always false for w1 and gives duplicateValueTernary for t1. The PR reports neither.

C113 check (n1.c, about 20 clamp-then-narrow variants):

  • All of C113's cases are reported again: (int8_t), (uint8_t), (short), and uint8_t c = x.
  • The PR also fixes several wrong base results where the clamped range does not fit the destination type. Examples: [0,300] cast with (uint8_t) and compared > 200; [-5,100] cast with (uint8_t) and compared == 251; [0,255] cast with (int8_t) and compared < 0; [-100,100] cast with (unsigned) and compared > 100u.
  • unsigned x <= 100 with (int8_t)x < 0 is a correct new warning.

Possible false positives (n2.c, n4.c): facts that are later invalidated gave no new false positives. I tried an assignment after the clamp, x *= 3, x++ in a loop, a conditional reassignment, facts from only one branch, and per-call function argument values.

Earlier reproducers (old.c, run on unix64 and win64): the earlier findings are fixed. I re-ran:

  • ~(uint32_t)x;
  • char == 0xFF;
  • y -= 1 after a cast;
  • signed char i++;
  • an unsigned loop index used as a[i + 1];
  • an && loop;
  • (char)0;
  • the 0x80000000 enum;
  • wchar_t == 0xFFFF.

Real code: base and PR on test/cfg/std.c, test/cfg/posix.c, lib/mathlib.cpp and lib/token.cpp give identical output (1542 lines each) in the same time (81.5 s for each).


Automated review of fc51719 by Claude. The pull request was built and tested locally.

Comment thread lib/vf_common.cpp Resolved

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

New false positives when a signed variable is compared with an unsigned constant of int rank or higher. With the PR, the literal in x >= 0x80000000u or x == 0xFFFFFFFFu has the value it has in the unsigned common type (2147483648, 4294967295). Base had -2147483648 and -1. The condition handler still gives these values to the int variable unchanged. The facts it derives can never hold for an int: x {!<=4294967294,>=4294967295}. So common checks like if (x >= 0x80000000u) { if (x < 0) … } now get oppositeInnerCondition ("dead code"), and if (x < 0x80000000u) return; if (x == -5) gets "always false". Both conditions are actually always true. In one case the PR turns base's correct "always true" into "always false". Base already has wrong results for some mixed-sign conditions, but the cases below are new or have the opposite answer.

The unit tests pass. C115 is fixed: &&, || and while uses are now reported. I checked 123 other new knownConditionTrueFalse results from generated cast/arithmetic code by compiling and running the code, and all of them were correct.

Earlier comments

68 earlier comments, 0 open
# Comment By Where Status
1 Warning text/ID wrong: 4294967295 fits signed long long @chrchr-github test/testcondition.cpp:6559 ✅ Fixed
2 Use getSizeOf instead of the switch over types @aadanen lib/checkcondition.cpp:1984 ✅ Fixed
3 Unknown sign should return false @aadanen lib/checkcondition.cpp:2020 ✅ Fixed
4 PR title should be updated @danmar general ✅ Fixed
5 C++ casts have two operands @danmar lib/checkcondition.cpp:2034 ❔ Code removed
6 Unclear which code is targeted @danmar lib/checkcondition.cpp:2050 ❔ Code removed
7 Always returns false for unary +/- @danmar lib/checkcondition.cpp:2059 ❔ Code removed
8 Use existing utility for integer type min/max @danmar lib/checkcondition.cpp:1975 ✅ Fixed
9 Check for similar existing utility @danmar lib/checkcondition.cpp:2019 ✅ Fixed
10 Pass platform instead of settings @danmar lib/checkcondition.cpp:2020 ❔ Code removed
11 Consider impossible values when no known value @danmar lib/checkcondition.cpp:2026 ✅ Fixed
12 Logic should be in ValueFlow, not the checker @chrchr-github general ✅ Fixed
13 Unsigned 64-bit max equals signed max @aadanen lib/vf_common.cpp:99 💬 Answered: bigint cannot represent ULLONG_MAX; conservative max kept
14 Use uint32_t instead of typedefs in tests @chrchr-github test/testcondition.cpp:6549 ✅ Fixed
15 Unsigned wrap-around FP for (uint32_t)x - 1u == 0xFFFFFFFFu @danmar lib/valueflow.cpp:1039 ✅ Fixed
16 getValueLE change affects all callers @claude[bot] lib/token.cpp:1932 ✅ Fixed
17 Value list copies, dead +|* path, dropping conditional values @claude[bot] lib/valueflow.cpp:5222 ✅ Fixed
18 Impossible bounds dropped for all unsigned arithmetic (FN risk) @claude[bot] lib/vf_settokenvalue.cpp:501 ✅ Fixed
19 getMinMaxValues returns false for UNKNOWN_SIGN @claude[bot] lib/vf_common.cpp:91 ✅ Fixed
20 containerOutOfBounds FP on resize guard AI review general ✅ Fixed
21 negativeIndex bypass ignores loop condition AI review general ✅ Fixed
22 No-wrap check loses existing knownConditionTrueFalse results AI review general ✅ Fixed
23 teststl expectation changed to accept FP AI review test/teststl.cpp:529 ✅ Fixed
24 Induction-variable bypass does not check loop condition AI review lib/checkbufferoverrun.cpp:401 ✅ Fixed
25 Range bounds dropped when no-wrap proof fails AI review lib/vf_settokenvalue.cpp:511 ✅ Fixed
26 uninitvar FP for float/long double after >=/<= AI review general ✅ Fixed
27 Value::unknown() used as float false-branch value AI review lib/valueflow.cpp:5120 ✅ Fixed
28 floatConversionOverflow FP from float bounds AI review general ✅ Fixed
29 Bounded float values read as concrete AI review lib/valueflow.cpp:5125 ✅ Fixed
30 Negative value cast to unsigned loses arrayIndexOutOfBoundsCond AI review general ✅ Fixed
31 negativeIndex lost when init may be negative AI review general ✅ Fixed
32 Plain char compared with 300 not reported AI review general ✅ Fixed
33 Check runs with --platform=unspecified AI review general ✅ Fixed
34 Bounded value dropped on cast instead of converted AI review lib/vf_settokenvalue.cpp:188 ✅ Fixed
35 Assignment version of negative-to-unsigned FN AI review lib/valueflow.cpp:4117 ✅ Fixed
36 any_of accepts init value that may be negative AI review lib/checkbufferoverrun.cpp:392 ✅ Fixed
37 Plain char skipped in compareValueOutOfTypeRange AI review lib/checkcondition.cpp:2328 ✅ Fixed
38 Unspecified platform early return removed AI review lib/checkcondition.cpp:2072 ✅ Fixed
39 arrayIndexOutOfBounds lost for a[i+1] with unsigned loop index AI review general ✅ Fixed
40 Loop range dropped at unsigned +/* in setTokenValue AI review lib/vf_settokenvalue.cpp:641 ✅ Fixed
41 FN after for loop with && condition AI review general ✅ Fixed
42 Bitfield width leaks into result type of ~ in dump AI review general ✅ Fixed
43 valueFlowForLoopSimplifyAfter skipped for partial conditions AI review lib/valueflow.cpp:5679 ✅ Fixed
44 getCommonIntegralType copies whole ValueType AI review lib/symboldatabase.cpp:7552 ✅ Fixed
45 Plain signed char compared with 0xFF no longer reported AI review general ✅ Fixed
46 Checker ignores platform.defaultSign for plain char AI review lib/checkcondition.cpp:2129 ✅ Fixed
47 #11592 regression test expectation changed to empty AI review test/testcondition.cpp:6846 ✅ Fixed
48 Bitfield width leaks on ++/-- path AI review general ✅ Fixed
49 ++/-- copies operand's whole ValueType AI review lib/symboldatabase.cpp:7531 ✅ Fixed
50 ~ on cast bounds does not flip bound kind (FP) AI review general ✅ Fixed
51 ~ handler keeps bound direction AI review lib/valueflow.cpp:1051 ✅ Fixed
52 y -= 1 / y-- after cast reported as never wrapping AI review general ✅ Fixed
53 evalAssignment shifts bound without no-wrap check AI review lib/valueflow.cpp:1053 ✅ Fixed
54 Narrow signed i++ after cast treated as non-wrapping AI review general ✅ Fixed
55 Guard only stops unsigned types in vf_analyzers AI review lib/vf_analyzers.cpp:286 ✅ Fixed
56 Cast to plain char drops all values AI review general ✅ Fixed
57 castValue returns false for UNKNOWN_SIGN char AI review lib/vf_settokenvalue.cpp:226 ✅ Fixed
58 wchar_t treated as signed 16-bit on Windows (FP) AI review general ✅ Fixed
59 wchar_t range from getSizeOf with SIGNED fallback AI review lib/checkcondition.cpp:2134 ✅ Fixed
60 Enum compared with 0x80000000 enumerator reported always false AI review general ✅ Fixed
61 Known value trusted to fit enum's signed int type AI review lib/checkcondition.cpp:2128 ✅ Fixed
62 || loop gives possible lastValue+1 past init (zerodiv FP) AI review general ✅ Fixed
63 After-loop value ignores initValue > lastValue AI review lib/valueflow.cpp:5686 ✅ Fixed
64 Still-open items: resize guard, unsigned loop index, plain char @danmar general ✅ Fixed
65 Bounded value loses range through narrowing cast/assignment AI review general ✅ Fixed
66 Bounds converted one by one, clamp-then-narrow lost AI review lib/vf_settokenvalue.cpp:248 ✅ Fixed
67 Clamp-then-narrow lost when cast is in the same &&/||/?:/while condition AI review general ✅ Fixed
68 conditionBranchAtUse rejects uses in RHS of &&/||/?: AI review lib/vf_common.cpp:472 ✅ Fixed

Testing

Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestType, TestStl, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.

CLI tests: pytest other_test.py -k "15000 or floating or unsigned_loop or bounded or cast" gives 4 passed.

Differential test with an oracle: I generated 30 files with 150 functions each. Each function has a random guard on x, then nested casts, arithmetic and ~ on x, then a comparison. I ran base and the PR (--platform=unix64). For every knownConditionTrueFalse that only the PR reports, I compiled the file with gcc -fwrapv and ran the function over about 4000 values of x, including the type limits.

  • 123 of the new results were correct.
  • 3 were wrong. All three have a signed x compared with an unsigned constant in the guard.

Reduced reproducer (r.c):

void use(int);
void r1(int x) { if (x >= 0x80000000u) { if (x < 0) use(1); } }
void r2(int x) { if (x < 0x80000000u) return; if (x == -5) use(2); }
void r5(int x) { if (x == 0xFFFFFFFFu) { if (x == -1) use(5); } }
void m6(int x) { if (x < 4294967295u || x >= 127) return; if (x * 255 - 150 < 65535) use(6); }
void m9(int x) { if (x < 4294967295u) return; if (x == -1) use(9); }
void m2(int x) { if (x < 1u || x >= 4294967295u) return; if (~x != 1) use(3); }

Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}' r.c

PR, line by line:

  • r1: oppositeInnerCondition: Opposite inner 'if' condition leads to a dead code block. Base gives nothing. For int x, x >= 0x80000000u holds exactly when x < 0.
  • r2: Condition 'x==-5' is always false. Base gives nothing. It is true for x == -5.
  • r5: oppositeInnerCondition. Base says Condition 'x==-1' is always true, which is correct.
  • m6: Condition 'x*255-150<65535' is always false. Base says always true, which is correct: only x == -1 reaches it, and that gives -405.
  • m9: Condition 'x==-1' is always false. Base gives nothing. It is always true.
  • m2: Condition '~x!=1' is always true. Base gives nothing. It is false for x == -2.

--debug for m9:

  • PR: 4294967295u always 4294967295 and x {!<=4294967294,>=4294967295}
  • base: 4294967295u always -1 and x {!<=-2,>=-1}

C115 check: x >= 0 && x <= 100 && (uint8_t)x > 200, (int8_t)x < 0, the || form and the while form are reported again. With a ternary ((x>=0&&x<=100) ? (uint8_t)x>200 : 0), neither version reports the condition. Base's duplicateValueTernary is still lost, as C114 already noted.

Possible false positives: I checked facts that are made invalid before the use:

  • x = 250, x *= 3 or ++x inside the && chain;
  • set(&x) or *p = 250 after the check;
  • a write in a loop body, a goto back edge, a switch fall-through, and the else branch.

None gave a false positive.


Automated review of dcb0cec by Claude. The pull request was built and tested locally.

Comment thread lib/vf_settokenvalue.cpp Resolved

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The mixed-sign fix for C116/C117 is incomplete, and the PR still reports false positives that base does not. castConstantToOperandType() returns early unless the unsigned constant is a literal token. When the constant comes from an unsigned variable, a const variable, a cast like (unsigned)-1, or ~0u, the signed variable still gets an impossible value: int x becomes always 4294967295. With the PR this gives:

  • oppositeInnerCondition and "always false" on x == -1, which is always true; base says "always true", which is correct.
  • integerOverflowCond false positives.
  • The real zerodivcond in 10 / (x + 1) is no longer reported.

The literal cases from C117 (r1, r2, r5, m9) are fixed now. C116's ~x != 1 case (m2) is still wrongly reported as always true.

All the unit tests and the PR's CLI tests pass.

Earlier comments

66 earlier comments, 2 open
# Comment By Where Status
1 Warning text/ID wrong: 4294967295 fits signed long long @chrchr-github test/testcondition.cpp:6559 ✅ Fixed
2 Use getSizeOf instead of the switch over types @aadanen lib/checkcondition.cpp:1984 ✅ Fixed
3 Unknown sign should return false @aadanen lib/checkcondition.cpp:2020 ✅ Fixed
4 PR title should be updated @danmar general ✅ Fixed
5 C++ casts have two operands @danmar lib/checkcondition.cpp:2034 ❔ Code removed
6 Unclear which code is targeted @danmar lib/checkcondition.cpp:2050 ❔ Code removed
7 Always returns false for unary +/- @danmar lib/checkcondition.cpp:2059 ❔ Code removed
8 'signed long long' in the message is confusing @danmar test/testcondition.cpp:6559 ✅ Fixed
9 Use existing utility for integer type min/max @danmar lib/checkcondition.cpp:1975 ✅ Fixed
10 Check for a similar existing utility @danmar lib/checkcondition.cpp:2019 ✅ Fixed
11 Pass platform instead of settings @danmar lib/checkcondition.cpp:2020 ❔ Code removed
12 Consider impossible values when there is no known value @danmar lib/checkcondition.cpp:2026 ✅ Fixed
13 Logic should be in ValueFlow, not in the checker @chrchr-github general ✅ Fixed
14 Unsigned 64-bit max equals signed max @aadanen lib/vf_common.cpp:99 💬 Answered: bigint cannot represent ULLONG_MAX; conservative max kept
15 Use uint32_t instead of typedefs in tests @chrchr-github test/testcondition.cpp:6549 ✅ Fixed
16 Unsigned wrap-around FP for (uint32_t)x - 1u == 0xFFFFFFFFu @danmar lib/valueflow.cpp:1038 ✅ Fixed
17 getValueLE change affects all callers @claude[bot] lib/token.cpp:1932 ✅ Fixed
18 Value list copies and dropped conditional values @claude[bot] lib/valueflow.cpp:5222 ✅ Fixed
19 Impossible bounds dropped for all unsigned arithmetic @claude[bot] lib/vf_settokenvalue.cpp:501 ✅ Fixed
20 getMinMaxValues returns false for UNKNOWN_SIGN @claude[bot] lib/vf_common.cpp:91 ✅ Fixed
21 containerOutOfBounds FP, negativeIndex bypass, lost knownConditionTrueFalse results AI review general ✅ Fixed
22 teststl expectation changed to accept FP AI review test/teststl.cpp:529 ✅ Fixed
23 Induction-variable bypass ignores loop condition AI review lib/checkbufferoverrun.cpp:401 ✅ Fixed
24 Range bounds dropped when no-wrap proof fails AI review lib/vf_settokenvalue.cpp:511 ✅ Fixed
25 uninitvar FP for float after >=/<= AI review general ✅ Fixed
26 Value::unknown() used as float false-branch value AI review lib/valueflow.cpp:5120 ✅ Fixed
27 floatConversionOverflow FP from float bounds AI review general ✅ Fixed
28 Bounded float values read as concrete AI review lib/valueflow.cpp:5124 ✅ Fixed
29 Negative-to-unsigned FN, negativeIndex FN, char==300 FN, unspecified platform AI review general ✅ Fixed
30 Bounded value dropped on cast instead of converted AI review lib/vf_settokenvalue.cpp:188 ✅ Fixed
31 Assignment version of negative-to-unsigned FN AI review lib/valueflow.cpp:4116 ✅ Fixed
32 any_of accepts init value that may be negative AI review lib/checkbufferoverrun.cpp:392 ✅ Fixed
33 Plain char skipped in compareValueOutOfTypeRange AI review lib/checkcondition.cpp:2328 ✅ Fixed
34 Unspecified platform early return removed AI review lib/checkcondition.cpp:2072 ✅ Fixed
35 arrayIndexOutOfBounds lost for a[i+1] with unsigned index AI review general ✅ Fixed
36 Loop range dropped at unsigned +/* in setTokenValue AI review lib/vf_settokenvalue.cpp:641 ✅ Fixed
37 FN after for loop with && condition; bitfield width leak AI review general ✅ Fixed
38 valueFlowForLoopSimplifyAfter skipped for partial conditions AI review lib/valueflow.cpp:5678 ✅ Fixed
39 getCommonIntegralType copies whole ValueType AI review lib/symboldatabase.cpp:7552 ✅ Fixed
40 Plain signed char compared with 0xFF no longer reported AI review general ✅ Fixed
41 Checker ignores platform.defaultSign for plain char AI review lib/checkcondition.cpp:2129 ✅ Fixed
42 #11592 regression test expectation changed AI review test/testcondition.cpp:6846 ✅ Fixed
43 Bitfield width leaks on ++/-- AI review general ✅ Fixed
44 ++/-- copies operand's whole ValueType AI review lib/symboldatabase.cpp:7531 ✅ Fixed
45 ~ on cast bounds does not flip bound kind (FP) AI review general ✅ Fixed
46 ~ handler keeps bound direction AI review lib/valueflow.cpp:1050 ✅ Fixed
47 y -= 1 / y-- after cast treated as never wrapping AI review general ✅ Fixed
48 evalAssignment shifts bound without no-wrap check AI review lib/valueflow.cpp:1052 ✅ Fixed
49 Narrow signed i++ after cast treated as non-wrapping AI review general ✅ Fixed
50 Guard only stops unsigned types in vf_analyzers AI review lib/vf_analyzers.cpp:286 ✅ Fixed
51 Cast to plain char drops all values AI review general ✅ Fixed
52 castValue returns false for UNKNOWN_SIGN char AI review lib/vf_settokenvalue.cpp:226 ✅ Fixed
53 wchar_t treated as signed 16-bit on Windows AI review general ✅ Fixed
54 wchar_t range from getSizeOf with SIGNED fallback AI review lib/checkcondition.cpp:2134 ✅ Fixed
55 Enum compared with 0x80000000 enumerator reported always false AI review general ✅ Fixed
56 Known value trusted to fit enum's signed int type AI review lib/checkcondition.cpp:2128 ✅ Fixed
57 || loop gives possible lastValue+1 (zerodiv FP) AI review general ✅ Fixed
58 After-loop value ignores initValue > lastValue AI review lib/valueflow.cpp:5685 ✅ Fixed
59 Still-open items from earlier reviews AI review general ✅ Fixed
60 Comment on still-open items (resize guard, unsigned loop index, plain char) @danmar general ✅ Fixed
61 Bounded value loses range through narrowing cast/assignment AI review general ✅ Fixed
62 Bounds converted one by one, clamp-then-narrow lost AI review lib/vf_settokenvalue.cpp:248 ✅ Fixed
63 Clamp-then-narrow lost in same &&/||/?:/while condition AI review general ✅ Fixed
64 conditionBranchAtUse rejects uses in RHS of &&/||/?: AI review lib/vf_common.cpp:472 ✅ Fixed
65 Signed variable compared with unsigned constant gets impossible values (FPs) AI review general ⚠️ Open
66 Condition handler gives unsigned-domain constant to signed variable AI review lib/vf_settokenvalue.cpp:117 ⚠️ Open

@jfdeverge, please fix, resolve or reply to the open comments: #65, #66.

Testing

Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestType, TestStl, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.

CLI tests: pytest other_test.py -k "15000 or floating or unsigned_loop or bounded or cast" gives 4 passed.

C116/C117 reproducers (r.c, --platform=unix64):

  • r1, r2, r5 and m9 are now correct.
  • m2 (if (x < 1u || x >= 4294967295u) return; if (~x != 1)) is still reported as Condition '~x!=1' is always true.

New: the fix only covers literal constants (v.c)

void use(int);
void v1(int x) { unsigned u = 0xFFFFFFFFu; if (x == u) { if (x == -1) use(1); } }
void v2(int x) { const unsigned M = 0xFFFFFFFFu; if (x == M) { if (x == -1) use(2); } }
void v3(int x) { if (x == (unsigned)-1) { if (x == -1) use(3); } }
void v4(int x) { if (x == ~0u) { if (x == -1) use(4); } }
void v5(int x) { unsigned u = 0xFFFFFFFFu; if (x != u) return; if (x == -1) use(5); }
void v6(int x) { unsigned u = 0xFFFFFFFFu; if (x == u) { use(x + 1); } }
int  v7(int x) { unsigned u = 0xFFFFFFFFu; if (x == u) { return 10 / (x + 1); } return 0; }

Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}' v.c

Base output (correct):

2..6:knownConditionTrueFalse:Condition 'x==-1' is always true
8:zerodivcond:Either the condition 'x==u' is redundant or there is division by zero at line 8.

PR output:

2:oppositeInnerCondition:Opposite inner 'if' condition leads to a dead code block.
3:oppositeInnerCondition:Opposite inner 'if' condition leads to a dead code block.
4:oppositeInnerCondition:Opposite inner 'if' condition leads to a dead code block.
5:oppositeInnerCondition:Opposite inner 'if' condition leads to a dead code block.
6:knownConditionTrueFalse:Condition 'x==-1' is always false
7:integerOverflowCond:Either the condition 'x==u' is redundant or there is signed integer overflow for expression 'x+1'.
8:integerOverflowCond:Either the condition 'x==u' is redundant or there is signed integer overflow for expression 'x+1'.

--debug for v1:

  • PR: u always 4294967295, x always {4294967295,symbolic=(u)}
  • base: x always {-1,symbolic=(u)}

Not changed by the PR: base and the PR give the same wrong results for ordering comparisons of a signed variable with 0x80000000u. Examples: if (x >= 0x80000000u) return; if (x < 0) is reported as always true, and if (x < 0x80000000u) { if (x < 0) } is reported as always true.


Automated review of d117ac7 by Claude. The pull request was built and tested locally.

Comment thread lib/vf_common.cpp Resolved

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

New false positives in the mixed-sign fix (ValueFlow::castConstantToOperandType, lib/vf_common.cpp:144-146). The function truncates an unsigned constant to the size of the signed operand. But the comparison happens in the common type, which is at least int and at least as wide as the constant. When the operand is narrower than that type (short/signed char compared with 0xFFFFu/0x8000u/0xFFu, or int with 0xFFFFFFFFul on LP64), the operand is sign-extended first. So 0xFFFFu is not -1 for a short, and no short value equals it. The PR maps it to -1 anyway, then derives facts for that -1 in the condition handler, so reachable conditions are reported as always false or always true. Base gives none of these warnings. I confirmed this by running compiled code: for short s = -1, s == 0xFFFFu is false.

C116's ~x != 1 case (m2) is still reported as always true, as C118 already says. The earlier reproducers from C118/C119 are fixed now. Apart from the new bug above, I found nothing new.

Earlier comments

68 earlier comments, 1 open
# Comment By Where Status
1 Warning text/ID wrong: 4294967295 is in range for signed long long @chrchr-github test/testcondition.cpp:6559 ✅ Fixed
2 Use getSizeOf instead of the switch over types @aadanen lib/checkcondition.cpp:1984 ✅ Fixed
3 Unknown sign should return false, not be treated as unsigned @aadanen lib/checkcondition.cpp:2020 ✅ Fixed
4 PR title should be updated @danmar general ✅ Fixed
5 C++ casts have two operands @danmar lib/checkcondition.cpp:2034 ❔ Code removed
6 Unclear which code is targeted @danmar lib/checkcondition.cpp:2050 ❔ Code removed
7 Always returns false for unary +/- @danmar lib/checkcondition.cpp:2059 ❔ Code removed
8 Use an existing utility for integer type min/max @danmar lib/checkcondition.cpp:1975 ✅ Fixed
9 Check for a similar existing utility function @danmar lib/checkcondition.cpp:2019 ✅ Fixed
10 Pass platform instead of settings @danmar lib/checkcondition.cpp:2020 ❔ Code removed
11 Consider impossible values when there is no known value @danmar lib/checkcondition.cpp:2026 ✅ Fixed
12 Logic should be in ValueFlow, not in the checker @chrchr-github general ✅ Fixed
13 Unsigned 64-bit max equals signed max @aadanen lib/vf_common.cpp:99 💬 Answered: bigint cannot represent ULLONG_MAX; conservative max kept
14 Use uint32_t instead of typedefs in tests @chrchr-github test/testcondition.cpp:6549 ✅ Fixed
15 Unsigned wrap FP: (uint32_t)x - 1u == 0xFFFFFFFFu @danmar lib/valueflow.cpp:1038 ✅ Fixed
16 containerOutOfBounds FP on resize guard AI review general ✅ Fixed
17 negativeIndex bypass ignores the loop condition AI review general ✅ Fixed
18 No-wrap check loses s+1u==0u and i+1==0 results AI review general ✅ Fixed
19 teststl expectation changed to accept the containerOutOfBounds FP AI review test/teststl.cpp:529 ✅ Fixed
20 Induction-variable bypass does not check the loop condition AI review lib/checkbufferoverrun.cpp:401 ✅ Fixed
21 Range bounds dropped when the no-wrap proof fails AI review lib/vf_settokenvalue.cpp:511 ✅ Fixed
22 uninitvar FP for float/long double after >=/<= AI review general ✅ Fixed
23 Value::unknown() used as float false-branch value AI review lib/valueflow.cpp:5120 ✅ Fixed
24 floatConversionOverflow FP from float bounds AI review general ✅ Fixed
25 Bounded float values read as concrete values AI review lib/valueflow.cpp:5124 ✅ Fixed
26 Negative value cast to unsigned loses arrayIndexOutOfBoundsCond AI review general ✅ Fixed
27 negativeIndex lost when the init may be negative AI review general ✅ Fixed
28 Plain char compared with 300 not reported AI review general ✅ Fixed
29 Check runs with --platform=unspecified AI review general ✅ Fixed
30 Bounded value dropped on a cast instead of converted AI review lib/vf_settokenvalue.cpp:188 ✅ Fixed
31 Assignment version of the negative-to-unsigned FN AI review lib/valueflow.cpp:4116 ✅ Fixed
32 any_of accepts an init that has some negative values AI review lib/checkbufferoverrun.cpp:392 ✅ Fixed
33 Plain char skipped in compareValueOutOfTypeRange AI review lib/checkcondition.cpp:2328 ✅ Fixed
34 Unspecified platform early return removed AI review lib/checkcondition.cpp:2072 ✅ Fixed
35 arrayIndexOutOfBounds lost for a[i+1] with an unsigned loop index AI review general ✅ Fixed
36 Loop range dropped at unsigned +/* AI review lib/vf_settokenvalue.cpp:641 ✅ Fixed
37 FN after a for loop with an && condition AI review general ✅ Fixed
38 Bitfield width leaks into the result type of ~ AI review general ✅ Fixed
39 valueFlowForLoopSimplifyAfter skipped for partial conditions AI review lib/valueflow.cpp:5678 ✅ Fixed
40 getCommonIntegralType copies the whole ValueType (bits) AI review lib/symboldatabase.cpp:7552 ✅ Fixed
41 Plain signed char compared with 0xFF not reported AI review general ✅ Fixed
42 Checker ignores platform.defaultSign for plain char AI review lib/checkcondition.cpp:2129 ✅ Fixed
43 #11592 regression test expectation changed to empty AI review test/testcondition.cpp:6846 ✅ Fixed
44 Bitfield width leaks on the ++/-- path AI review general ✅ Fixed
45 ++/-- copies the whole ValueType incl. bits AI review lib/symboldatabase.cpp:7531 ✅ Fixed
46 ~ on cast bounds does not flip the bound kind (FP) AI review general ✅ Fixed
47 ~ handler keeps the bound direction AI review lib/valueflow.cpp:1050 ✅ Fixed
48 y -= 1 / y-- after a cast reported as never wrapping AI review general ✅ Fixed
49 evalAssignment shifts the bound without the no-wrap check AI review lib/valueflow.cpp:1052 ✅ Fixed
50 Narrow signed i++ after a cast treated as non-wrapping AI review general ✅ Fixed
51 Guard only stops unsigned types in vf_analyzers AI review lib/vf_analyzers.cpp:286 ✅ Fixed
52 Cast to plain char drops all values AI review general ✅ Fixed
53 castValue returns false for UNKNOWN_SIGN char AI review lib/vf_settokenvalue.cpp:226 ✅ Fixed
54 wchar_t treated as signed 16-bit on Windows (FP) AI review general ✅ Fixed
55 wchar_t range from getSizeOf with SIGNED fallback AI review lib/checkcondition.cpp:2134 ✅ Fixed
56 Enum compared with a 0x80000000 enumerator reported always false AI review general ✅ Fixed
57 Known value trusted to fit the enum's signed int type AI review lib/checkcondition.cpp:2128 ✅ Fixed
58 || loop gives possible lastValue+1 past init (zerodiv FP) AI review general ✅ Fixed
59 After-loop value ignores initValue > lastValue AI review lib/valueflow.cpp:5685 ✅ Fixed
60 Still-open items: resize guard FP, unsigned loop index FN, plain char 0xFF FN @danmar general ✅ Fixed
61 Clamp-then-narrow cast loses the bounded range AI review general ✅ Fixed
62 Each bound converted on its own on a narrowing cast AI review lib/vf_settokenvalue.cpp:248 ✅ Fixed
63 Clamp-then-narrow fails in an &&/||/?:/while condition AI review general ✅ Fixed
64 conditionBranchAtUse rejects uses in the RHS of &&/||/?: AI review lib/vf_common.cpp:472 ✅ Fixed
65 Signed variable vs unsigned constant gives wrong facts (m2: ~x!=1 always true) AI review general ⚠️ Open
66 Unsigned literal value given unchanged to a signed variable AI review lib/vf_settokenvalue.cpp:117 ✅ Fixed
67 Mixed-sign fix covers only literal constants AI review general ✅ Fixed
68 Only literal tokens are converted in castConstantToOperandType AI review lib/vf_common.cpp:124 ✅ Fixed

@jfdeverge, please fix, resolve or reply to the open comments: #65.

Testing

Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.

CLI tests: pytest other_test.py -k "15000 or floating or unsigned_loop or bounded or cast or missing_include" gives 8 passed.

New false positives: narrow signed operand compared with a wider unsigned constant

x.c:

void use(int);
void b1(short s) { if (s == 0xFFFFu) return; if (s == -1) use(1); }
void b2(int x) { if (x == 0xFFFFFFFFul) return; if (x == -1) use(2); }
void b3(signed char c) { if (c != 0xFFu) { if (c == -1) use(3); } }
void b4(short s) { if (s == 0xFFFFu) {} else { if (s == -1) use(4); } }

Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}' x.c

  • Base: only the correct compareValueOutOfTypeRangeError warnings (s == 0xFFFFu is always false, and so on).
  • PR: the same warnings, plus these:
2:knownConditionTrueFalse:Condition 's==-1' is always false
3:knownConditionTrueFalse:Condition 'x==-1' is always false
4:knownConditionTrueFalse:Condition 'c==-1' is always false
5:knownConditionTrueFalse:Condition 's==-1' is always false

All four conditions are reachable with the value -1 and are then true. A gcc check of short s=-1; s==0xFFFFu, signed char c=-1; c==0xFFu and int x=-1; x==0xFFFFFFFFul prints 0 0 0.

Relational form (y.c):

void use(int);
void c1(short s) { if (s >= 0x8000u) return; if (s < 0) use(1); if (s == 5) use(11); }
void c2(short s) { if (s < 0x8000u) { if (s == 5) use(2); } }
  • PR:
    • 2: Condition 's<0' is always true
    • 2: Condition 's==5' is always false
    • 3: oppositeInnerCondition
  • Correct behaviour: after the guard, s is in [0, 32767], so s<0 is always false and s==5 is possible.
  • Base: gives only compareValueOutOfTypeRangeError here.

--debug shows that the constant is turned into -1 or -32768 for the short operand.

Earlier findings re-checked with the PR:

  • These are fixed:
    • the C118 reproducers (x == u, x == M, (unsigned)-1, ~0u, x != u, the 10 / (x + 1) zerodivcond);
    • the literal cases r1 and m9;
    • the resize guard;
    • a[i + 1] with an unsigned loop index;
    • char == 0xFF;
    • ~(uint32_t)x;
    • the flag enum;
    • the && loop;
    • the clamp-then-narrow && chain;
    • the float uninitvar case;
    • y -= 1 after a cast;
    • a negative value cast to unsigned.
  • C116's if (x < 1u || x >= 4294967295u) return; if (~x != 1) is still reported as Condition '~x!=1' is always true.

Automated review of fa04208 by Claude. The pull request was built and tested locally.

Comment thread lib/vf_common.cpp Resolved

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

I found one new problem. It is a false negative that base does not have: a for loop whose start value has only an excluded lower bound no longer gets its negativeIndex warning. For example, void n1(unsigned char n) { for (int i = n - 1; i < 10; i++) a[i] = 0; } gives a[-1] when n == 0. Base reports negativeIndex (index -1), and the PR reports nothing. The cause is the new rule in valueFlowForLoop that an impossible bound "does not witness its endpoint". Here the endpoint can be reached, because n can be 0. If this is intended, a Trac ticket would cover it, as danmar suggested for false negatives.

The latest reported false positive (C120/C121: short/signed char compared with a wider unsigned constant) is fixed in this version. C116's ~x != 1 case is still reported as always true. I found no other new problems.

Earlier comments

70 earlier comments, 1 open
# Comment By Where Status
1 Warning text/ID wrong: 4294967295 is in range for signed long long @chrchr-github test/testcondition.cpp:6559 ✅ Fixed
2 Use getSizeOf instead of the switch over types @aadanen lib/checkcondition.cpp:1984 ✅ Fixed
3 Unknown sign should return false, not be treated as unsigned @aadanen lib/checkcondition.cpp:2020 ✅ Fixed
4 PR title should be updated @danmar general ✅ Fixed
5 C++ casts have two operands @danmar lib/checkcondition.cpp:2034 ❔ Code removed
6 Unclear which code is targeted @danmar lib/checkcondition.cpp:2050 ❔ Code removed
7 Always returns false for unary +/- @danmar lib/checkcondition.cpp:2059 ❔ Code removed
8 Use an existing utility for integer type min/max @danmar lib/checkcondition.cpp:1975 ✅ Fixed
9 Check for a similar existing utility function @danmar lib/checkcondition.cpp:2019 ✅ Fixed
10 Pass platform instead of settings @danmar lib/checkcondition.cpp:2020 ❔ Code removed
11 Consider impossible values when there is no known value @danmar lib/checkcondition.cpp:2026 ✅ Fixed
12 Logic should be in ValueFlow, not in the checker @chrchr-github general ✅ Fixed
13 Unsigned 64-bit max equals the signed max @aadanen lib/vf_common.cpp:99 💬 Answered: bigint cannot represent ULLONG_MAX; the conservative max is kept
14 Use uint32_t instead of typedefs in tests @chrchr-github test/testcondition.cpp:6549 ✅ Fixed
15 Unsigned wrap FP: (uint32_t)x - 1u == 0xFFFFFFFFu @danmar lib/valueflow.cpp:1038 ✅ Fixed
16 containerOutOfBounds FP on the resize guard AI review general ✅ Fixed
17 negativeIndex bypass ignores the loop condition AI review general ✅ Fixed
18 No-wrap check loses s+1u==0u and i+1==0 AI review general ✅ Fixed
19 teststl expectation changed to accept the containerOutOfBounds FP AI review test/teststl.cpp:529 ✅ Fixed
20 Induction-variable bypass does not check the loop condition AI review lib/checkbufferoverrun.cpp:401 ✅ Fixed
21 Range bounds dropped when the no-wrap proof fails AI review lib/vf_settokenvalue.cpp:511 ✅ Fixed
22 uninitvar FP for float/long double after >=/<= AI review general ✅ Fixed
23 Value::unknown() used as the float false-branch value AI review lib/valueflow.cpp:5120 ✅ Fixed
24 floatConversionOverflow FP from float bounds AI review general ✅ Fixed
25 Bounded float values read as concrete values AI review lib/valueflow.cpp:5124 ✅ Fixed
26 Negative value cast to unsigned loses arrayIndexOutOfBoundsCond AI review general ✅ Fixed
27 negativeIndex lost when the init may be negative AI review general ✅ Fixed
28 Plain char compared with 300 not reported AI review general ✅ Fixed
29 Check runs with --platform=unspecified AI review general ✅ Fixed
30 Bounded value dropped on a cast instead of converted AI review lib/vf_settokenvalue.cpp:188 ✅ Fixed
31 Assignment version of the negative-to-unsigned FN AI review lib/valueflow.cpp:4116 ✅ Fixed
32 any_of accepts an init that has some negative values AI review lib/checkbufferoverrun.cpp:392 ✅ Fixed
33 Plain char skipped in compareValueOutOfTypeRange AI review lib/checkcondition.cpp:2328 ✅ Fixed
34 Unspecified-platform early return removed AI review lib/checkcondition.cpp:2072 ✅ Fixed
35 arrayIndexOutOfBounds lost for a[i+1] with an unsigned loop index AI review general ✅ Fixed
36 Loop range dropped at unsigned +/* AI review lib/vf_settokenvalue.cpp:641 ✅ Fixed
37 FN after a for loop with an && condition AI review general ✅ Fixed
38 Bitfield width leaks into the result type of ~ AI review general ✅ Fixed
39 valueFlowForLoopSimplifyAfter skipped for partial conditions AI review lib/valueflow.cpp:5678 ✅ Fixed
40 getCommonIntegralType copies the whole ValueType (bits) AI review lib/symboldatabase.cpp:7552 ✅ Fixed
41 Plain signed char compared with 0xFF not reported AI review general ✅ Fixed
42 Checker ignores platform.defaultSign for plain char AI review lib/checkcondition.cpp:2129 ✅ Fixed
43 #11592 regression test expectation changed to empty AI review test/testcondition.cpp:6846 ✅ Fixed
44 Bitfield width leaks on the ++/-- path AI review general ✅ Fixed
45 ++/-- copies the whole ValueType including bits AI review lib/symboldatabase.cpp:7531 ✅ Fixed
46 ~ on cast bounds does not flip the bound kind (FP) AI review general ✅ Fixed
47 ~ handler keeps the bound direction AI review lib/valueflow.cpp:1050 ✅ Fixed
48 y -= 1 / y-- after a cast reported as never wrapping AI review general ✅ Fixed
49 evalAssignment shifts the bound without the no-wrap check AI review lib/valueflow.cpp:1052 ✅ Fixed
50 Narrow signed i++ after a cast treated as non-wrapping AI review general ✅ Fixed
51 Guard only stops unsigned types in vf_analyzers AI review lib/vf_analyzers.cpp:286 ✅ Fixed
52 Cast to plain char drops all values AI review general ✅ Fixed
53 castValue returns false for UNKNOWN_SIGN char AI review lib/vf_settokenvalue.cpp:226 ✅ Fixed
54 wchar_t treated as signed 16-bit on Windows (FP) AI review general ✅ Fixed
55 wchar_t range from getSizeOf with the SIGNED fallback AI review lib/checkcondition.cpp:2134 ✅ Fixed
56 Enum compared with a 0x80000000 enumerator reported always false AI review general ✅ Fixed
57 Known value trusted to fit the enum's signed int type AI review lib/checkcondition.cpp:2128 ✅ Fixed
58 || loop gives possible lastValue+1 past init (zerodiv FP) AI review general ✅ Fixed
59 After-loop value ignores initValue > lastValue AI review lib/valueflow.cpp:5685 ✅ Fixed
60 Still-open items: resize guard FP, unsigned loop index FN, plain char 0xFF FN @danmar general ✅ Fixed
61 Clamp-then-narrow cast loses the bounded range AI review general ✅ Fixed
62 Each bound converted on its own on a narrowing cast AI review lib/vf_settokenvalue.cpp:248 ✅ Fixed
63 Clamp-then-narrow fails in an &&/||/?:/while condition AI review general ✅ Fixed
64 conditionBranchAtUse rejects uses in the RHS of &&/||/?: AI review lib/vf_common.cpp:472 ✅ Fixed
65 Signed variable vs unsigned constant gives wrong facts (~x != 1 always true) AI review general ⚠️ Open
66 Unsigned literal given unchanged to a signed variable in the condition handler AI review lib/vf_settokenvalue.cpp:117 ✅ Fixed
67 Mixed-sign fix covers only literal constants AI review general ✅ Fixed
68 Only literal tokens converted in castConstantToOperandType AI review lib/vf_common.cpp:124 ✅ Fixed
69 Narrow signed operand vs wider unsigned constant gives FPs AI review general ✅ Fixed
70 Constant truncated to operand size instead of the common type AI review lib/vf_common.cpp:146 ✅ Fixed

@jfdeverge, please fix, resolve or reply to the open comments: #65.

Testing

Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.

CLI tests: pytest other_test.py -k "15000 or floating or unsigned_loop or bounded or cast or missing_include" gives 8 passed.

Base vs PR on real files: I ran both with --enable=style,warning,portability --platform=unix64 --library=posix on test/cfg/std.c, std.cpp, posix.c, lib/mathlib.cpp and lib/token.cpp. The only difference is that compareValueOutOfTypeRangeError is no longer reported for bool == 123 in std.cpp. That is intended: compareBoolExpressionWithInt already covers it, and the PR removes the matching suppressions.

New false negative: negativeIndex for a loop start value with only an excluded lower bound

l8.c:

int a[10];
void n1(unsigned char n) { for (int i = n - 1; i < 10; i++) a[i] = 0; }
void n2(unsigned short n) { for (int i = n - 2; i < 10; i++) a[i] = 0; }
void n3(unsigned char n) { for (int i = (int)n - 1; i < 10; i++) a[i] = 0; }
void l7(unsigned char u) { for (int i = u - 300; i < 10; i++) a[i] = 0; }

Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}' l8.c

Base:

2:negativeIndex:Array 'a[10]' accessed at index -1, which is out of bounds.
3:negativeIndex:Array 'a[10]' accessed at index -2, which is out of bounds.
4:negativeIndex:Array 'a[10]' accessed at index -1, which is out of bounds.
5:negativeIndex:Array 'a[10]' accessed at index -300, which is out of bounds.

PR: no output.

All of these indexes really occur (n == 0, u == 0). In --debug both versions show n - 1 with only !<=-2. The PR's for-loop code only forwards an impossible upper bound, or a possible or known witness, so this start value is dropped. if (x < -5) return; for (int i = x; …) is still reported, through the condition.

Re-checked earlier findings with the PR:

  • These are all correct now:
    • C120/C121 (short s == 0xFFFFu, x == 0xFFFFFFFFul, c != 0xFFu, s >= 0x8000u);
    • C37 (uint32_t)x - 1u == 0xFFFFFFFFu;
    • the resize guard;
    • i-- > -3;
    • s + 1u == 0u;
    • a[i + 1] with an unsigned index;
    • ~(uint32_t)x;
    • wchar_t on win64;
    • the flag enum;
    • the || loop zerodiv;
    • char == 0xFF;
    • clamp-then-narrow;
    • the float uninitvar case;
    • (char)0 zerodiv;
    • the && loop;
    • the x == u variable constant.
  • Still wrong: C116 m2, void m2(int x) { if (x < 1u || x >= 4294967295u) return; if (~x != 1) use(3); }, is reported as Condition '~x!=1' is always true.
  • Wrong in base and the PR alike, so not caused by the PR:
    • const unsigned short M = 0xFFFF; if (s == M) return; if (s == -1) gives s==-1 always false.
    • if (x > 0x7FFFFFFFu) { if (x >= 0) } gives x>=0 always true.

The #15000 reproducer gives Condition '(((sint64)((uint32)tmp))-1LL)>4294967295LL' is always false.

Comments

lib/valueflow.cpp:1945

This drops negativeIndex warnings that base gives and that are real. When the start value of the loop only has an impossible lower bound, that bound now goes forward only as a constraint. Often the endpoint can be reached:

int a[10];
void n1(unsigned char n) { for (int i = n - 1; i < 10; i++) a[i] = 0; }   // a[-1] when n == 0
void n2(unsigned short n) { for (int i = n - 2; i < 10; i++) a[i] = 0; }  // a[-2]

Base reports negativeIndex at index -1 and -2. The PR reports nothing (--platform=unix64). The !<=-2 here comes from n >= 0 on an unsigned operand. The minimum is reached when n == 0. Could a lower bound that comes from the type's own range (unsigned operand, or a cast) be treated as a witness? If this is intended, please open a Trac ticket and add a TODO test.


Automated review of a89fcd0 by Claude. The pull request was built and tested locally.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

I found no new problems in this version.

  • Still open: the false positive first reported in C116 is still there. In void m2(int x) { if (x < 1u || x >= 4294967295u) return; if (~x != 1) use(3); } the PR reports Condition '~x!=1' is always true. That is wrong: for x == -2, ~x == 1. Base gives a different wrong result on this function (x>=4294967295u always true).
  • Fixed: the C122 negativeIndex false negative (for (int i = n - 1; ...) with an unsigned n). The "tight exclusion" witness in valueFlowForLoop brings back all of base's warnings.
  • Reproducer: the #15000 case is reported as knownConditionTrueFalse.
  • No new false positives: none of the extra cast, arithmetic, mixed-sign and for-loop cases I tried gave a new false positive. In several of them the PR removes a wrong result that base gives.

Earlier comments

75 earlier comments, 1 open
# Comment By Where Status
1 Warning text/ID wrong: 4294967295 is in range for signed long long @chrchr-github test/testcondition.cpp:6559 ✅ Fixed
2 Use getSizeOf instead of the switch over types @aadanen lib/checkcondition.cpp:1984 ✅ Fixed
3 Unknown sign should return false, not be treated as unsigned @aadanen lib/checkcondition.cpp:2020 ✅ Fixed
4 PR title should be updated @danmar general ✅ Fixed
5 C++ casts have two operands @danmar lib/checkcondition.cpp:2034 ❔ Code removed
6 Unclear which code is targeted @danmar lib/checkcondition.cpp:2050 ❔ Code removed
7 Always returns false for unary +/- @danmar lib/checkcondition.cpp:2059 ❔ Code removed
8 Use an existing utility for integer type min/max @danmar lib/checkcondition.cpp:1975 ✅ Fixed
9 Check for a similar existing utility function @danmar lib/checkcondition.cpp:2019 ✅ Fixed
10 Pass platform instead of settings @danmar lib/checkcondition.cpp:2020 ❔ Code removed
11 Consider impossible values when there is no known value @danmar lib/checkcondition.cpp:2026 ✅ Fixed
12 Logic should be in ValueFlow, not in the checker @chrchr-github general ✅ Fixed
13 Unsigned 64-bit max equals the signed max @aadanen lib/vf_common.cpp:99 💬 Answered: bigint cannot represent ULLONG_MAX; conservative max kept
14 Use uint32_t instead of typedefs in tests @chrchr-github test/testcondition.cpp:6549 ✅ Fixed
15 Unsigned wrap FP: (uint32_t)x - 1u == 0xFFFFFFFFu @danmar lib/valueflow.cpp:1038 ✅ Fixed
16 getValueLE change affects all callers and hides an FP @claude[bot] lib/token.cpp:1932 ✅ Fixed
17 valueFlowInferCondition copies lists and drops conditional values @claude[bot] lib/valueflow.cpp:5222 ✅ Fixed
18 Impossible bounds dropped for all unsigned arithmetic; duplicated predicate @claude[bot] lib/vf_settokenvalue.cpp:501 ✅ Fixed
19 getMinMaxValues returns false for UNKNOWN_SIGN (plain char) @claude[bot] lib/vf_common.cpp:91 ✅ Fixed
20 containerOutOfBounds FP on the resize guard AI review general ✅ Fixed
21 negativeIndex bypass ignores the loop condition AI review general ✅ Fixed
22 No-wrap check loses s+1u==0u and i+1==0 AI review general ✅ Fixed
23 teststl expectation changed to accept the containerOutOfBounds FP AI review test/teststl.cpp:529 ✅ Fixed
24 Induction-variable bypass does not check the loop condition AI review lib/checkbufferoverrun.cpp:401 ✅ Fixed
25 Range bounds dropped when the no-wrap proof fails AI review lib/vf_settokenvalue.cpp:511 ✅ Fixed
26 uninitvar FP for float/long double after >=/<= AI review general ✅ Fixed
27 Value::unknown() used as the float false-branch value AI review lib/valueflow.cpp:5120 ✅ Fixed
28 floatConversionOverflow FP from float bounds AI review general ✅ Fixed
29 Bounded float values read as concrete values AI review lib/valueflow.cpp:5124 ✅ Fixed
30 Negative value cast to unsigned loses arrayIndexOutOfBoundsCond AI review general ✅ Fixed
31 negativeIndex lost when the init may be negative AI review general ✅ Fixed
32 Plain char compared with 300 not reported AI review general ✅ Fixed
33 Check runs with --platform=unspecified AI review general ✅ Fixed
34 Bounded value dropped on a cast instead of converted AI review lib/vf_settokenvalue.cpp:188 ✅ Fixed
35 Assignment version of the negative-to-unsigned FN AI review lib/valueflow.cpp:4116 ✅ Fixed
36 any_of accepts an init that has some negative values AI review lib/checkbufferoverrun.cpp:392 ✅ Fixed
37 Plain char skipped in compareValueOutOfTypeRange AI review lib/checkcondition.cpp:2328 ✅ Fixed
38 Unspecified-platform early return removed AI review lib/checkcondition.cpp:2072 ✅ Fixed
39 arrayIndexOutOfBounds lost for a[i+1] with an unsigned loop index AI review general ✅ Fixed
40 Loop range dropped at unsigned +/* AI review lib/vf_settokenvalue.cpp:641 ✅ Fixed
41 FN after a for loop with an && condition AI review general ✅ Fixed
42 Bitfield width leaks into the result type of ~ AI review general ✅ Fixed
43 valueFlowForLoopSimplifyAfter skipped for partial conditions AI review lib/valueflow.cpp:5700 ✅ Fixed
44 getCommonIntegralType copies the whole ValueType (bits) AI review lib/symboldatabase.cpp:7552 ✅ Fixed
45 Plain signed char compared with 0xFF not reported AI review general ✅ Fixed
46 Checker ignores platform.defaultSign for plain char AI review lib/checkcondition.cpp:2129 ✅ Fixed
47 #11592 regression test expectation changed to empty AI review test/testcondition.cpp:6846 ✅ Fixed
48 Bitfield width leaks on the ++/-- path AI review general ✅ Fixed
49 ++/-- copies the whole ValueType including bits AI review lib/symboldatabase.cpp:7531 ✅ Fixed
50 ~ on cast bounds does not flip the bound kind (FP) AI review general ✅ Fixed
51 ~ handler keeps the bound direction AI review lib/valueflow.cpp:1050 ✅ Fixed
52 y -= 1 / y-- after a cast reported as never wrapping AI review general ✅ Fixed
53 evalAssignment shifts the bound without the no-wrap check AI review lib/valueflow.cpp:1052 ✅ Fixed
54 Narrow signed i++ after a cast treated as non-wrapping AI review general ✅ Fixed
55 Guard only stops unsigned types in vf_analyzers AI review lib/vf_analyzers.cpp:286 ✅ Fixed
56 Cast to plain char drops all values AI review general ✅ Fixed
57 castValue returns false for UNKNOWN_SIGN char AI review lib/vf_settokenvalue.cpp:226 ✅ Fixed
58 wchar_t treated as signed 16-bit on Windows (FP) AI review general ✅ Fixed
59 wchar_t range from getSizeOf with the SIGNED fallback AI review lib/checkcondition.cpp:2134 ✅ Fixed
60 Enum compared with a 0x80000000 enumerator reported always false AI review general ✅ Fixed
61 Known value trusted to fit the enum's signed int type AI review lib/checkcondition.cpp:2128 ✅ Fixed
62 || loop gives possible lastValue+1 past init (zerodiv FP) AI review general ✅ Fixed
63 After-loop value ignores initValue > lastValue AI review lib/valueflow.cpp:5707 ✅ Fixed
64 Still-open items: resize guard FP, unsigned loop index FN, plain char 0xFF FN, char sign mismatch @danmar general ✅ Fixed
65 Clamp-then-narrow cast loses the bounded range AI review general ✅ Fixed
66 Each bound converted on its own on a narrowing cast AI review lib/vf_settokenvalue.cpp:248 ✅ Fixed
67 Clamp-then-narrow fails in an &&/||/?:/while condition AI review general ✅ Fixed
68 conditionBranchAtUse rejects uses in the RHS of &&/||/?: AI review lib/vf_common.cpp:472 ✅ Fixed
69 Signed variable vs unsigned constant gives wrong facts (~x != 1 always true) AI review general ⚠️ Open
70 Unsigned literal given unchanged to a signed variable in the condition handler AI review lib/vf_settokenvalue.cpp:117 ✅ Fixed
71 Mixed-sign fix covers only literal constants AI review general ✅ Fixed
72 Only literal tokens converted in castConstantToOperandType AI review lib/vf_common.cpp:124 ✅ Fixed
73 Narrow signed operand vs wider unsigned constant gives FPs AI review general ✅ Fixed
74 Constant truncated to operand size instead of the common type AI review lib/vf_common.cpp:146 ✅ Fixed
75 negativeIndex lost for loop start with only an excluded lower bound AI review general ✅ Fixed

@jfdeverge, please fix, resolve or reply to the open comments: #69.

Testing

Build: make -j8 cppcheck testrunner in pr/ and make cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0. I did not run the Python CLI tests this time.

How I compared: every result below compares base and PR using cppcheck -q --enable=style,warning,portability --platform=unix64 --template='{line}:{id}:{message}' <file>.

Re-checked earlier findings

C122 is fixed. Test file l8.c, with these extra lines:

  • u * 2 - 3
  • u - 1 - 1
  • -(int)u
  • int s = u - 1; used as the start value
  • if (x < -5) return;

The PR reports every negativeIndex that base reports. It also adds one for for (int i = -(int)u; ...), where base gives none. The reported index there is -2147483647, though the real minimum is -255.

C116 m2 is still open:

void use(int);
void m2(int x) { if (x < 1u || x >= 4294967295u) return; if (~x != 1) use(3); }
  • Base: 2:knownConditionTrueFalse:Condition 'x>=4294967295u' is always true. This is wrong too.
  • PR: 2:knownConditionTrueFalse:Condition '~x!=1' is always true. This is wrong, because x == -2 passes the guard and gives ~x == 1.

The #15000 reproducer, written with stdint.h types, gives Condition '(((int64_t)((uint32_t)tmp))-1LL)>4294967295LL' is always false.

New probes (p1.c, p2.c, p3.c)

p1.c, about 25 cases: casts combined with + - * / % << >> &, and == against unsigned constants. There are no new false positives. There is one new correct result: uint8_t c = (uint8_t)x; c + 1 > 256 is always false.

p2.c: mixed-sign ==/< against unsigned constants, oppositeInnerCondition, and for-loop start values. Results:

  • The results match base except for three improvements:
    • x <= 0xFFFFFFFFu is now correctly reported as always true.
    • Base's wrong result for signed char c == 0xFFFFFFFFu is gone.
    • Base's false negativeIndex for for (int i = n - 1; i < 10 && n; i++) is gone.
  • Two wrong results are the same in base and the PR, so the PR did not cause them:
    • if (x >= 0x80000000u) { if (x == 0x80000000u) } gives oppositeInnerCondition.
    • x >= 0xFFFFFFF0u && x < 5 gives incorrectLogicOperator.

p3.c: the at-minimum and at-maximum paths of the rewritten checkCompareValueOutOfTypeRange (INT_MIN <= x, s < 0xFFFFFFFFu, 0xFFFFFFFFu > s, s < 0x80000000u, bool, unsigned char and short). The PR removes four wrong "always true" results from base: lines 7, 11 and 22, all short against an unsigned constant. It gives no new false positives.

Real code: I ran both versions on lib/checkcondition.cpp, lib/mathlib.cpp and cli/cmdlineparser.cpp. The warnings were identical. The PR took 394 s and base 346 s, a single run each, so I could not tell whether the difference is noise.


Automated review of bcd8c72 by Claude. The pull request was built and tested locally.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

I found no new problems in this version.

  • Still open (already in comments.md, C116): void m2(int x) { if (x < 1u || x >= 4294967295u) return; if (~x != 1) use(3); } is still reported as Condition '~x!=1' is always true. That is wrong, because x == -2 passes the guard and gives ~x == 1. I did not report it again.
  • Earlier findings: every other finding from the earlier reviews (C37–C122) that I re-ran now gives the correct result.
  • New probes: I tried casts, arithmetic, out-of-range comparisons, mixed-sign comparisons, for loops, per-call-path inference, float bounds and C++ casts. They gave no new false positives, false negatives or crashes. In several cases the PR removes a wrong base result, for example:
    • short s; s > 0xFFFFu was reported as always false;
    • signed char c; c > 200u was reported as always false;
    • uint64_t x; x == -1 was reported as always false.
  • Real code: base and PR gave identical warnings, and the run time was the same.

Earlier comments

75 earlier comments, 1 open
# Comment By Where Status
1 Warning text/ID wrong: 4294967295 is in range for signed long long @chrchr-github test/testcondition.cpp:6559 ✅ Fixed
2 Use getSizeOf instead of the switch over types @aadanen lib/checkcondition.cpp:1984 ✅ Fixed
3 Unknown sign should return false, not be treated as unsigned @aadanen lib/checkcondition.cpp:2020 ✅ Fixed
4 PR title should be updated @danmar general ✅ Fixed
5 C++ casts have two operands @danmar lib/checkcondition.cpp:2034 ❔ Code removed
6 Unclear which code is targeted @danmar lib/checkcondition.cpp:2050 ❔ Code removed
7 Always returns false for unary +/- @danmar lib/checkcondition.cpp:2059 ❔ Code removed
8 Use an existing utility for integer type min/max @danmar lib/checkcondition.cpp:1975 ✅ Fixed
9 Check for a similar existing utility function @danmar lib/checkcondition.cpp:2019 ✅ Fixed
10 Pass platform instead of settings @danmar lib/checkcondition.cpp:2020 ❔ Code removed
11 Consider impossible values when there is no known value @danmar lib/checkcondition.cpp:2026 ✅ Fixed
12 Logic should be in ValueFlow, not in the checker @chrchr-github general ✅ Fixed
13 Unsigned 64-bit max equals the signed max @aadanen lib/vf_common.cpp:99 💬 Answered: bigint cannot represent ULLONG_MAX; the conservative max is kept
14 Use uint32_t instead of typedefs in tests @chrchr-github test/testcondition.cpp:6549 ✅ Fixed
15 Unsigned wrap FP: (uint32_t)x - 1u == 0xFFFFFFFFu @danmar lib/valueflow.cpp:1038 ✅ Fixed
16 getValueLE change affects all callers and hides an FP @claude[bot] lib/token.cpp:1932 ✅ Fixed
17 valueFlowInferCondition copies lists and drops conditional values @claude[bot] lib/valueflow.cpp:5222 ✅ Fixed
18 Impossible bounds dropped for all unsigned arithmetic; duplicated predicate @claude[bot] lib/vf_settokenvalue.cpp:501 ✅ Fixed
19 getMinMaxValues returns false for UNKNOWN_SIGN (plain char) @claude[bot] lib/vf_common.cpp:91 ✅ Fixed
20 containerOutOfBounds FP on the resize guard AI review general ✅ Fixed
21 negativeIndex bypass ignores the loop condition AI review general ✅ Fixed
22 No-wrap check loses s+1u==0u and i+1==0 AI review general ✅ Fixed
23 teststl expectation changed to accept the containerOutOfBounds FP AI review test/teststl.cpp:529 ✅ Fixed
24 Induction-variable bypass does not check the loop condition AI review lib/checkbufferoverrun.cpp:401 ✅ Fixed
25 Range bounds dropped when the no-wrap proof fails AI review lib/vf_settokenvalue.cpp:511 ✅ Fixed
26 uninitvar FP for float/long double after >=/<= AI review general ✅ Fixed
27 Value::unknown() used as the float false-branch value AI review lib/valueflow.cpp:5120 ✅ Fixed
28 floatConversionOverflow FP from float bounds AI review general ✅ Fixed
29 Bounded float values read as concrete values AI review lib/valueflow.cpp:5124 ✅ Fixed
30 Negative value cast to unsigned loses arrayIndexOutOfBoundsCond AI review general ✅ Fixed
31 negativeIndex lost when the init may be negative AI review general ✅ Fixed
32 Plain char compared with 300 not reported AI review general ✅ Fixed
33 Check runs with --platform=unspecified AI review general ✅ Fixed
34 Bounded value dropped on a cast instead of converted AI review lib/vf_settokenvalue.cpp:188 ✅ Fixed
35 Assignment version of the negative-to-unsigned FN AI review lib/valueflow.cpp:4116 ✅ Fixed
36 any_of accepts an init that has some negative values AI review lib/checkbufferoverrun.cpp:392 ✅ Fixed
37 Plain char skipped in compareValueOutOfTypeRange AI review lib/checkcondition.cpp:2328 ✅ Fixed
38 Unspecified-platform early return removed AI review lib/checkcondition.cpp:2072 ✅ Fixed
39 arrayIndexOutOfBounds lost for a[i+1] with an unsigned loop index AI review general ✅ Fixed
40 Loop range dropped at unsigned +/* AI review lib/vf_settokenvalue.cpp:641 ✅ Fixed
41 FN after a for loop with an && condition AI review general ✅ Fixed
42 Bitfield width leaks into the result type of ~ AI review general ✅ Fixed
43 valueFlowForLoopSimplifyAfter skipped for partial conditions AI review lib/valueflow.cpp:5701 ✅ Fixed
44 getCommonIntegralType copies the whole ValueType (bits) AI review lib/symboldatabase.cpp:7552 ✅ Fixed
45 Plain signed char compared with 0xFF not reported AI review general ✅ Fixed
46 Checker ignores platform.defaultSign for plain char AI review lib/checkcondition.cpp:2129 ✅ Fixed
47 #11592 regression test expectation changed to empty AI review test/testcondition.cpp:6846 ✅ Fixed
48 Bitfield width leaks on the ++/-- path AI review general ✅ Fixed
49 ++/-- copies the whole ValueType including bits AI review lib/symboldatabase.cpp:7531 ✅ Fixed
50 ~ on cast bounds does not flip the bound kind (FP) AI review general ✅ Fixed
51 ~ handler keeps the bound direction AI review lib/valueflow.cpp:1050 ✅ Fixed
52 y -= 1 / y-- after a cast reported as never wrapping AI review general ✅ Fixed
53 evalAssignment shifts the bound without the no-wrap check AI review lib/valueflow.cpp:1052 ✅ Fixed
54 Narrow signed i++ after a cast treated as non-wrapping AI review general ✅ Fixed
55 Guard only stops unsigned types in vf_analyzers AI review lib/vf_analyzers.cpp:286 ✅ Fixed
56 Cast to plain char drops all values AI review general ✅ Fixed
57 castValue returns false for UNKNOWN_SIGN char AI review lib/vf_settokenvalue.cpp:226 ✅ Fixed
58 wchar_t treated as signed 16-bit on Windows (FP) AI review general ✅ Fixed
59 wchar_t range from getSizeOf with the SIGNED fallback AI review lib/checkcondition.cpp:2134 ✅ Fixed
60 Enum compared with a 0x80000000 enumerator reported always false AI review general ✅ Fixed
61 Known value trusted to fit the enum's signed int type AI review lib/checkcondition.cpp:2128 ✅ Fixed
62 || loop gives possible lastValue+1 past init (zerodiv FP) AI review general ✅ Fixed
63 After-loop value ignores initValue > lastValue AI review lib/valueflow.cpp:5708 ✅ Fixed
64 Still-open items: resize guard FP, unsigned loop index FN, plain char 0xFF FN, char sign mismatch @danmar general ✅ Fixed
65 Clamp-then-narrow cast loses the bounded range AI review general ✅ Fixed
66 Each bound converted on its own on a narrowing cast AI review lib/vf_settokenvalue.cpp:248 ✅ Fixed
67 Clamp-then-narrow fails in an &&/||/?:/while condition AI review general ✅ Fixed
68 conditionBranchAtUse rejects uses in the RHS of &&/||/?: AI review lib/vf_common.cpp:472 ✅ Fixed
69 Signed variable vs unsigned constant: '~x!=1' wrongly always true after guard AI review general ⚠️ Open
70 Unsigned literal given unchanged to a signed variable in the condition handler AI review lib/vf_settokenvalue.cpp:117 ✅ Fixed
71 Mixed-sign fix covers only literal constants AI review general ✅ Fixed
72 Only literal tokens converted in castConstantToOperandType AI review lib/vf_common.cpp:124 ✅ Fixed
73 Narrow signed operand vs wider unsigned constant gives FPs AI review general ✅ Fixed
74 Constant truncated to operand size instead of the common type AI review lib/vf_common.cpp:146 ✅ Fixed
75 negativeIndex lost for loop start with only an excluded lower bound AI review general ✅ Fixed

@jfdeverge, please fix, resolve or reply to the open comments: #69.

Testing

Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.

CLI tests: pytest other_test.py -k "15000 or floating or unsigned_loop or bounded or cast or missing_include" gives 8 passed.

Earlier reproducers (old.c, w.c, s.cpp, bf.c)

  • I re-ran about 30 reproducers from C37–C122 on unix64, plus the wchar_t case on win64.
  • All of them now give correct results, with one exception: C116's m2 still gives 5:knownConditionTrueFalse:Condition '~x!=1' is always true.
  • The bitfield dump check gives bits="0" for ~ and ++.
  • The #11592 expectation is restored.

New probes: each one compares base and PR with cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}'.

  • a.c, about 30 cast and arithmetic cases:
    • Covered: shifts, / -1, <<=, *=, += with wrap, unary minus on casts, _Bool casts, bitfields and 64-bit wrap.
    • No new false positives.
    • The PR removes base's wrong results for uint64_t u = x; u + 1 == 0, unsigned u = -(uint8_t)x; u > 255, uint8_t y += 200; y < 100 and y += 0xFFFFFF00u; y < 10.
  • b.c, plain char with --funsigned-char, --fsigned-char and --platform=unspecified: the new results are correct for an unsigned char ((char)x == -1 is always false), and there is no output with the unspecified platform.
  • c.c, per-call-path inference: functions called with several argument pairs, and values from conditions. There are two correct new warnings:
    • negativeIndex in a[x - y] for the call f1(1,2);
    • zerodiv in 100 / (x - y) for the call f4(5,5).
    • I found no false "always" conditions.
  • d.c, float >=/<= guards followed by other comparisons, sqrt and int casts: same results as base.
  • e.c, about 32 compareValueOutOfTypeRange cases on unix64, win64 and unix32: every result the PR gives is correct. The PR removes four wrong base results (short/signed char against unsigned constants) and two wrong base results for uint64_t/unsigned long against -1.
  • f.c, for loops with cast start values or limits: same results as base.
  • g.c, mixed-sign comparisons, including long long against 0xFFFFFFFFu, short against 0xFFFFFFFFu and int against 0xFFFF…ull:
    • short s; if (s == 0xFFFFFFFFu) { if (s == -1) } is now correctly reported as always true; base gave a wrong oppositeInnerCondition.
    • int x; if (0xFFFFFFFFu == x) { if (x == -1) } is now correctly reported as always true; base said always false.
  • h.cpp, C++ casts: static_cast to an enum class, templates, functional casts, constexpr and '\xff'. The only new result is unsigned char c; c == '\xff' always false, which is correct.

Real code: I ran both builds with -j3 --enable=style,warning,portability --platform=unix64 --library=posix on lib/checkother.cpp, lib/checkstl.cpp, cli/cmdlineparser.cpp, test/cfg/windows.cpp and test/cfg/gnu.c. The output is identical. The PR took 452 s and base 450 s.

Seen but not caused by the PR: size_t n; std::vector<int> v; if (v.size() < n + 1) is reported as always true by both base and the PR. The PR removes the plain-variable versions of this wrong result (0 < n + 1, n + 1u != 0u).


Automated review of 98a4f1b by Claude. The pull request was built and tested locally.

Comment thread lib/vf_common.cpp Fixed

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

I found no new problems. The PR now handles correctly the last open item from earlier reviews (C116, ~x != 1 after if (x < 1u || x >= 4294967295u) return;). It no longer reports that condition. Base reported x>=4294967295u as always true there, which was also wrong.

On my probes every result that differs from base is either a correct new warning or a removed wrong base warning. The probes covered casts with arithmetic and compound assignment, loops with cast start values, clamp-and-narrow, mixed-sign comparisons (including constants of promoted rank such as (unsigned short)0xFFFF against short), enums, bitfields, char16_t/char32_t and C++ casts. Examples:

  • (uint16_t) wrap on y + 1: no longer wrongly always false.
  • (unsigned)x / (uint64_t)x of a value that may be negative: no longer wrongly always false.
  • x < 0x80000000u followed by x < 0: base said always true (wrong); the PR says always false (correct).

One wrong result is not caused by the PR: if (x > 5u) { if (x < 0) ... } with int x gives a wrong oppositeInnerCondition in both base and the PR, even though the PR changed isOppositeCond for mixed-sign constants.

Earlier comments

71 earlier comments, 0 open
# Comment By Where Status
1 Warning text/ID wrong: 4294967295 is in range for signed long long @chrchr-github test/testcondition.cpp:6559 ✅ Fixed
2 Use getSizeOf instead of switch over types @aadanen lib/checkcondition.cpp:1984 ✅ Fixed
3 Unknown sign should return false @aadanen lib/checkcondition.cpp:2020 ✅ Fixed
4 PR title should be updated @danmar general ✅ Fixed
5 C++ casts have two operands @danmar lib/checkcondition.cpp:2034 ❔ Code removed
6 Unclear which code is targeted @danmar lib/checkcondition.cpp:2050 ❔ Code removed
7 Always returns false for unary +/- @danmar lib/checkcondition.cpp:2059 ❔ Code removed
8 Use existing utility for integer type min/max @danmar lib/checkcondition.cpp:1975 ✅ Fixed
9 Check for similar existing utility function @danmar lib/checkcondition.cpp:2019 ✅ Fixed
10 Pass platform instead of settings @danmar lib/checkcondition.cpp:2020 ❔ Code removed
11 Consider impossible values when no known value @danmar lib/checkcondition.cpp:2026 ✅ Fixed
12 Logic should be in ValueFlow, not in the checker @chrchr-github general ✅ Fixed
13 Unsigned 64-bit max equals signed max @aadanen lib/vf_common.cpp:99 💬 Answered: bigint cannot represent ULLONG_MAX; conservative max kept
14 Use uint32_t instead of typedefs in tests @chrchr-github test/testcondition.cpp:6549 ✅ Fixed
15 Unsigned wrap FP: (uint32_t)x - 1u == 0xFFFFFFFFu @danmar lib/valueflow.cpp:1199 ✅ Fixed
16 containerOutOfBounds FP on resize guard AI review general ✅ Fixed
17 negativeIndex bypass ignores loop condition AI review general ✅ Fixed
18 No-wrap check loses s+1u==0u and i+1==0 AI review general ✅ Fixed
19 teststl expectation changed to accept FP AI review test/teststl.cpp:529 ✅ Fixed
20 Induction-variable bypass does not check loop condition AI review lib/checkbufferoverrun.cpp:401 ✅ Fixed
21 Range bounds dropped when no-wrap proof fails AI review lib/vf_settokenvalue.cpp:511 ✅ Fixed
22 uninitvar FP for float/long double after >=/<= AI review general ✅ Fixed
23 Value::unknown() used as float false-branch value AI review lib/valueflow.cpp:5120 ✅ Fixed
24 floatConversionOverflow FP from float bounds AI review general ✅ Fixed
25 Bounded float values read as concrete values AI review lib/valueflow.cpp:5288 ✅ Fixed
26 Negative value cast to unsigned loses arrayIndexOutOfBoundsCond AI review general ✅ Fixed
27 negativeIndex lost when init may be negative AI review general ✅ Fixed
28 Plain char compared with 300 not reported AI review general ✅ Fixed
29 Check runs with --platform=unspecified AI review general ✅ Fixed
30 Bounded value dropped on cast instead of converted AI review lib/vf_settokenvalue.cpp:188 ✅ Fixed
31 Assignment version of negative-to-unsigned FN AI review lib/valueflow.cpp:4277 ✅ Fixed
32 any_of accepts init with some negative values AI review lib/checkbufferoverrun.cpp:392 ✅ Fixed
33 Plain char skipped in compareValueOutOfTypeRange AI review lib/checkcondition.cpp:2328 ✅ Fixed
34 Unspecified-platform early return removed AI review lib/checkcondition.cpp:2072 ✅ Fixed
35 arrayIndexOutOfBounds lost for a[i+1] with unsigned loop index AI review general ✅ Fixed
36 Loop range dropped at unsigned +/* AI review lib/vf_settokenvalue.cpp:641 ✅ Fixed
37 FN after for loop with && condition AI review general ✅ Fixed
38 Bitfield width leaks into result type of ~ AI review general ✅ Fixed
39 valueFlowForLoopSimplifyAfter skipped for partial conditions AI review lib/valueflow.cpp:5865 ✅ Fixed
40 getCommonIntegralType copies whole ValueType AI review lib/symboldatabase.cpp:7552 ✅ Fixed
41 Plain signed char compared with 0xFF not reported AI review general ✅ Fixed
42 Checker ignores platform.defaultSign for plain char AI review lib/checkcondition.cpp:2129 ✅ Fixed
43 #11592 test expectation changed to empty AI review test/testcondition.cpp:6846 ✅ Fixed
44 Bitfield width leaks on ++/-- path AI review general ✅ Fixed
45 ++/-- copies whole ValueType including bits AI review lib/symboldatabase.cpp:7531 ✅ Fixed
46 ~ on cast bounds does not flip bound kind (FP) AI review general ✅ Fixed
47 ~ handler keeps bound direction AI review lib/valueflow.cpp:1211 ✅ Fixed
48 y -= 1 / y-- after cast reported as never wrapping AI review general ✅ Fixed
49 evalAssignment shifts bound without no-wrap check AI review lib/valueflow.cpp:1213 ✅ Fixed
50 Narrow signed i++ after cast treated as non-wrapping AI review general ✅ Fixed
51 Guard only stops unsigned types in vf_analyzers AI review lib/vf_analyzers.cpp:286 ✅ Fixed
52 Cast to plain char drops all values AI review general ✅ Fixed
53 castValue returns false for UNKNOWN_SIGN char AI review lib/vf_settokenvalue.cpp:226 ✅ Fixed
54 wchar_t treated as signed 16-bit on Windows (FP) AI review general ✅ Fixed
55 wchar_t range from getSizeOf with SIGNED fallback AI review lib/checkcondition.cpp:2134 ✅ Fixed
56 Enum compared with 0x80000000 enumerator reported always false AI review general ✅ Fixed
57 Known value trusted to fit enum's signed int type AI review lib/checkcondition.cpp:2128 ✅ Fixed
58 || loop gives possible lastValue+1 past init (zerodiv FP) AI review general ✅ Fixed
59 After-loop value ignores initValue > lastValue AI review lib/valueflow.cpp:5872 ✅ Fixed
60 Still-open items: resize guard FP, unsigned loop index FN, plain char 0xFF FN, char sign mismatch @danmar general ✅ Fixed
61 Clamp-then-narrow cast loses bounded range AI review general ✅ Fixed
62 Each bound converted on its own on narrowing cast AI review lib/vf_settokenvalue.cpp:248 ✅ Fixed
63 Clamp-then-narrow fails in &&/||/?:/while condition AI review general ✅ Fixed
64 conditionBranchAtUse rejects uses in RHS of &&/||/?: AI review lib/vf_common.cpp:472 ✅ Fixed
65 Signed variable vs unsigned constant: '~x!=1' wrongly always true after guard AI review general ✅ Fixed
66 Unsigned literal given unchanged to signed variable in condition handler AI review lib/vf_settokenvalue.cpp:117 ✅ Fixed
67 Mixed-sign fix covers only literal constants AI review general ✅ Fixed
68 Only literal tokens converted in castConstantToOperandType AI review lib/vf_common.cpp:124 ✅ Fixed
69 Narrow signed operand vs wider unsigned constant gives FPs AI review general ✅ Fixed
70 Constant truncated to operand size instead of common type AI review lib/vf_common.cpp:167 ✅ Fixed
71 negativeIndex lost for loop start with only excluded lower bound AI review general ✅ Fixed

Testing

Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.

Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.

CLI tests: pytest other_test.py -k "15000 or floating or unsigned or bounded or cast" gives 4 passed. These include the two new tests.

Probes: each one compares the PR and base with cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{column}:{id}:{message}'.

  • m2.c, the PR reproducer and C116's m2:
    • The PR reports the reproducer's condition as always false.
    • m2 is no longer reported.
    • Base gives a wrong x>=4294967295u always true.
  • p.c, short/signed char against unsigned short/unsigned char constants (variables, casts, ||, nested if): the new compareValueOutOfTypeRangeError results are all correct, because both operands are promoted to int. The knownConditionTrueFalse results are the same as base.
  • q.c, 22 cases of a value from (uint8_t)/(int8_t)/(uint16_t) followed by *=, +=, <<=, |=, ~, %, /, >>, unary minus and modification through a pointer or function:
    • The only new result is y = ~y; y > 255 always true, which is correct.
    • Base's wrong uint16_t y = y + 1; y == 0 always false is gone.
    • Base's wrong integerOverflowCond on int8 y * y is gone.
  • r.c, for loops with cast start values and limits, and INT_MIN/LLONG_MIN limits:
    • Results are the same as base, except that base's wrong compareValueOutOfTypeRangeError for i < -2147483647-1 is replaced by a correct knownConditionTrueFalse.
    • No crash.
  • s.cpp, enum class, bitfields, char16_t/char32_t, static_cast, functional casts, multiplication of casts, / -1, <<: the only new result is (uint32_t)x + 0ULL > 4294967295ULL always false, which is correct.
  • t.c, condition-bounded values followed by casts or wrapping arithmetic: the PR removes 7 wrong base results, for example if (x < -5 || x > 5) return; unsigned y = (unsigned)x; y > 5 always false, and if (x > 300) { uint8_t y = (uint8_t)x; y == 0 } always false. It adds none.
  • u.c, mixed-sign nested and else-if conditions:
    • x < 0x80000000u → x < 0: correctly always false; base said always true.
    • x <= 5u → x < 0: correctly always false.
    • x > 5u → x < 0: a wrong oppositeInnerCondition in both base and the PR, so not caused by the PR.

Real code: I ran lib/token.cpp with --enable=style,warning. The output is identical and both take 79 s.


Automated review of a66da09 by Claude. The pull request was built and tested locally.

@dmcppcheck

Copy link
Copy Markdown
Contributor

Test results for commit a66da09 (tools/test-my-pr.py, main compared to this PR):

Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-8819/
packages: 1000
Differing warnings: 4905 (+1711 -3194)
AI review: 1 acceptable regression, 19 improvement, 27 neutral, 3 regression (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-8819/2026-11-13_07-49-01-a66da095f678-review.txt)
Timing: +0.6% (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-8819/2026-11-13_07-49-01-a66da095f678_timing.html)

Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants